1. 安装React脚手架
// 全局安装create-react-app
npm install -g create-react-app
// 创建一个项目
create-react-app myapp(使用npx create-react-app myapp也可以)
// 删除src文件夹下的文件,然后在src下创建index.js以及App文件夹, 代码如下
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root')); // React 17写法
// 使用axios请求接口 npm i axios
// axios.get("请求地址").then(res => {}).catch(err => {console.log(err)})
axios({
url: "",
method: 'get', // 默认不写是get
headers: {
'X-Client-Info': '{'a': '3000'}'
}
}).then(res => {console.log(res.data)}).catch(err => {});
2. 安装路由
// 安装路由
npm install react-router-dom@5
// 编程式导航和声明式导航区别
1. 编程式导航直接使用location.href或者this.props.history(Router包裹的第一个组件才有, 函数式编程使用const history= useHistory()就可以使用)
2. 声明式直接使用NavLink
// 代码如下(含嵌套路由,使用嵌套路由一定不要用精确匹配exact)
import React, { useReducer, createContext, useContext } from 'react';
import {
HashRouter, // 路由会加#号
Route,
Redirect,
Switch,
NavLink, // 动态切换路由时会高亮现实,<NavLink to="films" activeClassName="kerwin">电影<NavLink />,css写个kerwin样式后链接就可以高亮显示
} from 'react-router-dom';
function SecondRouter() {
return (
<div>SecondRouter</div>
)
}
function SecondRouter1() {
return (
<div>SecondRouter1</div>
)
}
function Films() {
return (
<div>
<div>111111111</div>
{/* 嵌套路由配置 */}
<Switch>
<Route path="/films/secondRouter" component={SecondRouter} />
<Route path="/films/secondRouter1" component={SecondRouter1} />
<Redirect from="/films" to="/films/secondRouter" />
</Switch>
</div>
)
}
function NotFound() {
return (
<div>NotFound</div>
)
}
function Cinemas() {
return (
<div>2222</div>
)
}
function Center() {
return (
<div>3333</div>
)
}
class App extends React.Component {
render() {
return (
<HashRouter>
{/* Switch类似Swich语句,匹配到一个路由就不往下走,可以解决重定向问题 */}
{/* 一般写路由都会加Switch */}
<Switch>
{/**
一级路由 /films
二级路由 /films/aaa
...以此类推
*/}
<Route path="/films" component={Films} />
<Route path="/cinemas" component={Cinemas} />
<Route path="/center" component={Center} />
{/* exact不写代表模糊匹配,写了代表精准匹配 */}
{/* 重定向路由, 模糊匹配/,如果直接使用/,刷新页面后会一直重定向到films */}
<Redirect from="/" to="/films" exact />
{/* 都匹配不到直接跳转到NotFound */}
<Route component={NotFound} />
</Switch>
</HashRouter>
)
}
}
export default App;