react-router-dom

1,637 阅读2分钟
  1. 下载路由 npm react-router-dom --save-dev
  2. 在index.js文件中,配置基本路由

此处可以配置很多东西, 例如 路由的HTML5 History和 hash 两种路由模式

const Root = () => (
    <Provider {...new Store()}>  // 此处Store 是使用的mobx-react
        <BrowserRouter basename="/">
            <Rputer path={`/`} component={App} />
        </BrowserRouter>  // 设置路由模式
    </Provider>
    
)

在到App.js 或 新建一个router文件,配置具体页面

import React from 'react';
import {HashRouter, Route, Switch} from 'react-router-dom';
import Home from '../home';
import Detail from '../detail';


const BasicRoute = () => (
    <HashRouter>
        <Switch>   // 可以做路由权限设置
            <Route exact path="/" component={Home}/>
            <Route exact path="/detail" component={Detail}/>
        </Switch>
    </HashRouter>
);


export default BasicRoute;

export default BasicRoute;

  1. 路由跳转方式

a. 使用link跳转

<Link to='/test'>Link跳转</Link>

b. 使用history方法

this.props.history.push('detail')
  1. Url传参
  2. 在配置路由的时候传参 配置页面中:
<Route exact path="/detail/:id" component={Detail}/>

在组件中:

componentDidMount() {
    console.log(this.props.match.params);
}
  1. 使用this.this.props.history方法的时候传参
import React from 'react';


export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }
    
    render() {
        return (
            <div>
                <a href='#/detail/3'>去detail</a>
                    <button onClick={() => this.props.history.push({
                        pathname: '/detail',
                        state: {
                            id: 3
                        }
                })}>通过函数跳转</button>
            </div>
        )
    }
}

跳转的页面

componentDidMount() {
    //console.log(this.props.match.params);
    console.log(this.props.history.location.state);
}
  1. this.history的其他方法: a. replace 有些场景下,重复使用push或a标签跳转会产生死循环,为了避免这种情况出现,react-router-dom提供了replace。在可能会出现死循环的地方使用replace来跳转:
this.props.history.replace('/detail');

b. goBack 场景中需要返回上级页面的时候使用:

this.props.history.goBack();

注意点: 有一些组件公共组件也会要使用history里面的参数或方法,但如果不在配置文件的组件会报错,这时候就会使用withRouter这个api,可以使用@的方式引入就可以使用了

@withRouter   // 注意直接使用@会报错 需要配置
class Forback extends Component {
    ...
    fun() {
        this.props.history.push()
    }
    ...
}