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?
光陰似箭催人老,日月如移越少年。
react-router
傳遞參數(shù)無非通過url
里面的動態(tài)匹配或者query
To transfer, it is very clear in this document.
But in this login scenario, the better way is not to pass cookie
來進行登錄態(tài)的確定,從而使域名下的任何一個網頁都能知道已經登錄,而不需要像這樣傳遞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 你需要傳遞的狀態(tài)
query:query //傳遞方式2 顯示在路由路徑當中的query串,路由B也可以接收;
})
}
render …………
}
class B extends React.Component{
constructor(){
super();
}
componentWillMount(){
//當前傳遞過來的狀態(tài)
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
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