react配置路由

router.js

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
41
42
43
44
/**
* @name Router
* @desc 页面路由配置
*/

import React, { Component } from 'react'
import { Switch, Route, Redirect, Link } from 'react-router-dom'
import Home from './pages/Home'
import UserInfo from './pages/UserInfo'

class Router extends Component {
render() {
return (
<>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/home">About</Link>
</li>
<li>
<Link to="/detail">detail</Link>
</li>
</ul>
</nav>
<Switch>
<Redirect path="/" to="/home" exact />
<Route path="/home" component={Home} />
<Route path="/userinfo" component={UserInfo} />

{/* 404 */}
<Route path='/404' component={NotFoundPage} />

{/* 其他重定向到 404 */}
<Redirect from='*' to='/404' />
</Switch>
</>
)
}
}

export default Router

App.js

1
2
3
4
5
6
7
8
9
10
11
12
13
import './App.css';
import React from 'react'
import Routes from './router'

function App() {
return (
<div className="container">
<Routes />
</div>
);
}

export default App;

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom'

ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);

reportWebVitals();

路由指定拓展写法

1
<Route path="/detail" children={<Detail /> } />

路由传参

方式1 直接拼接

1
2
3
4
5
6
7
<!--路由指定:-->
<Route path="/detail/(:id)?" component={Detail } /> //路由表中
<Link to={ ' /detail/ ' + ' 2 ' } activeClassName='active'>detail</Link> //组件中
this.props.history.push( '/detail/'+'2' ) //任意组件js

<!--组件内部获取:-->
this.props.match.params.id
1
2
3
4
5
6
7
8
9
10
11
<!--*Tip:-->
<!--个人联想拓展:如果不想通过path/:id/1/title/:title/...的方式传递多个参数可以这样:-->
<!--传递-->
const params = { userid: 2, name: 'thomas' };
this.props.history.push(`/myurl/${ JSON.stringify(params)}`);
<!--获取-->
const { manyParams } = this.props.match.params;
// maynParams = "{"userid":2,"name":"thomas"}" //string获取
const { userid, name } = JSON.parse(manyParams); //Object解构
// userid = 1, name = thomas

方式2 通过query

1
2
3
4
5
6
7
8
9
10
11
12
13
<Link to={{ pathname : ' /detail ' , query : { name : 'sunny' }}}>

<!--前提:必须由其他页面跳过来,参数才会被传递过来-->
<!--注:不需要配置路由表。路由表中的内容照常:<Route path='/detail' component={Detail}></Route>-->
<!--1.Link处 -->
<!-- HTML方式-->
<Link to={{ pathname : ' /detail ' , query : { name : 'thomas' }}}>
          
<!--JS方式-->
this.props.history.push({ pathname : '/detail' ,query : { name: ' thomas'} })

<!--2.获取处页面 -->
this.props.location.query.name

方式3 通过state

1
<!--用法同query传参-->