创建项目:
1 2 3 |
npx create-react-app my-app cd my-app npm start |
添加路由
1 |
npm install --save react-router-dom |
新建 router 目录, 新建 index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import React from "react"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import Index from '../views/index'; import Demo from '../views/demo'; export default function BasicExample() { return ( <Router> <Switch> <Route exact path="/"> <Index /> </Route> <Route exact path="/demo"> <Demo /> </Route> </Switch> </Router> ); } |
遇到访问报错:
export ‘Switch‘ (imported as ‘Switch‘) was not found in ‘react-router
-dom‘
原因:这些报错原因均为’Switch’ 和’Redirect’ 是react-router 5版本的接口,而最新版本是
“react-router-dom”: “^6.2.1″,并且已经将Switch改为Routes。
解决: 办法有二:
1.将所有 Switch 改为 Routes,Redirect 改为 Navigate ,withRouter改为 useNavigate
2.卸载新版本,再安装5的版本
1 2 |
npm uninstall react-router-dom npm install react-router-dom@5 |
新建 jsx 文件:
新建 views目录.然后新建 index.jsx 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import React, { Component } from "react"; export default class App extends Component { constructor(props){ super(props) this.state = { goods: [ { title: '零售', price: 19.8 }, { title: '科技', price: 29.8 }, { title: '同城', price: 19.8 }, { title: '拼拼', price: 39.8 }, { title: '购物', price: 59.8 }, ], name: 'hello world' } } render() { return ( <div style={{padding: '20px'}}> <h1>{this.state.name}</h1> { this.state.goods.map((val,index)=> { return ( <div className="title" key={index}> <span> {val.title} </span> <span> {val.price} </span> </div> ) }) } </div> ); } componentDidMount(){ this.setState({ name: '我更新了' }) } componentDidUpdate(){} } |
路由处理
需要使用 withRouter 方法包裹抛出的 class, props 中会有 history 方法!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
goDemo() { // 隐式传参 this.props.history.push({ pathname: 'article', state: { id: 3, test: 1 }, query: { id: 3, test: 1 } }) } goDemo2(){ this.props.history.push('article?a=1') } goBack(){ this.props.history.goBack() } |