search

Home  >  Q&A  >  body text

javascript - Data transfer between react-router subpages

How to communicate when passing sub-pages?

import { HashRouter as Router, Route,  Link } from 'react-router-dom'

class Index extends Component {
  render() {
    return (
      <Router basename="/index">
        <p className="index-content" >
          <Link to="/library">library</Link>
          <Link to="/passbook">passbook</Link>
          <Link to="/login">login</Link>
          
          <br/>
          
          <Route path="/library" component={Library}/>
          <Route exact path="/passbook" component={Passbook}/>
          <Route path="/login" component={Login}/>
        </p>
      </Router>
    )
  }
}

export default Index;

1. The login page (#/index/login) uses this.state.isLogin to identify the login status. After logging in, this.state.isLogin becomes true

2. At this time, I switch to the passbook page (#/index/passbook) and need the isLogin of the login page (#/index/login) to determine which UI component should be rendered. How can I change the isLogin of the login page? Pass it to the passbook page?

大家讲道理大家讲道理2831 days ago878

reply all(4)I'll reply

  • 大家讲道理

    大家讲道理2017-05-19 10:42:04

    react-router传递参数无非通过url里面的动态匹配或者queryTo transfer, it is very clear in this document.

    But in this login scenario, the better way is not to pass cookie来进行登录态的确定,从而使域名下的任何一个网页都能知道已经登录,而不需要像这样传递state.

    reply
    0
  • 某草草

    某草草2017-05-19 10:42:04

    Two ways:
    The first one: put the state into a state machine through a redux-like idea, and take it as you want,
    The second way: use history transfer (route jump), if you jump from route A to route B, Route B component wants to get the data from Route A. You can do this:

       class A extends React.Component{
          constructor(){ super(); }
          handleClick(){
              browserHistory.push({
                 state:state //传递方式1 你需要传递的状态
                 query:query  //传递方式2  显示在路由路径当中的query串,路由B也可以接收;      
             })
          }
         render …………
       }
       
       class B extends React.Component{
          constructor(){
              super();
          }
          componentWillMount(){
              //当前传递过来的状态
              console.log(this.props.location.state)
          }
          render…………
      }
    

    Print this.props of the routing component and take a look. There are many things you need in it.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:42:04

    Use redux/flux to store login status
    And use cookie/LocalStorage/SessionStorage to store user login information,
    Otherwise, after refreshing the page, the status is still not logged in

    reply
    0
  • PHPz

    PHPz2017-05-19 10:42:04

    You can use react-redux to store the relevant required parameters in the store, and then connect each sub-component. The parameters of the store can be used as props

    reply
    0
  • Cancelreply