react-router simple to use

react-router version v4.x

Follow the example on the official website https://reacttraining.com/react-router/ learning

use

<Router>
    <header>
        <ul>
            <li><Link to='/home'>Home</Link</li>
            <li><Link to='/about'>About</Link</li>
            <li><Link to='/login'>Login</Link</li>
            <li><Link to='/register'>Register</Link</li>
        </ul>
    </header>
    <section>
        <Route path='/home' component={Home}/>
        <Route path='/about' component={About}/>
        <Route path='/login' component={Login}/>
        <Route path='/register' component={Register}/>
    </section>
    <footer>
        balabalabala...
    </footer>
</Router>

Note: When you click Link, when displayed in correspondence to Route corresponding components, in the section of Route is an alternative implementation, that is, when the click / home when the page section will show only part of the component content Home

By value

If you click on an item in the List, ID to pass to Detail years, this time you can use the following methods to achieve

<Route path='/detail/:id' render={(match) => (<Detail xxId={match.params.id}/>)}/>

Detail.jsx

class Detail extends React.Component 大专栏  react-router简单使用方法 class="p">{
    render() {
        console.log(this.props.xxId); //可以输出List里点击传过来的值
        return (<div></div>)
    }
}

In V4 where only the routing address by traditional values, and want to transfer more value, you can borrow to pass localStorage

Non-Link Jump

import {withRouter} from 'react-router-dom';

class ComponentA extends React.Component {
  //...
  _clickHandler() {
    this.props.history.push('/login');
  }
}

export default withRouter(ComponentA);

Routed back

<div onClick={()=>this.props.history.goBack()}>返回</div>

v2, v3 in the jump, and return by value

There are some different with v4, the following is v2, v3 in the wording

import {withRouter} from 'react-router';

class ComponentA extends React.Component {
  //...
  _clickHandler() {
    this.context.router.push('/login')
  }
  _goBackHandler() {
    this.context.router.goBack();
  }
}

ComponentA.contextTypes = {
  router: PropTypes.object.isRequired
};

export default withRouter(ComponentA);

The value from the route:

//路由定义
<Route path='/article/:id' component={Detail}/>

//在Detail组件里取值
const {id} = this.props.params;

problem

When you click to go from the List in Detail, and then click your browser's Back button, the status of the List component, there is no, I do not know why

NOTE: This problem can be solved by React-Router (v2, v3) + React-Router-Scroll, see blog: https://tomoya92.github.io/2017/09/06/reactjs-router-scroll/

Original link: https://chenyongze.github.io/2017/03/08/react-router-demo/

Guess you like

Origin www.cnblogs.com/lijianming180/p/12284662.html