javascript - Data transfer between react-router subpages
大家讲道理
大家讲道理 2017-05-19 10:40:04
0
4
817

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?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
大家讲道理

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.

某草草

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.

洪涛

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

PHPzhong

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template