郎朗坤
2019-06-09 15:32:20
使用Reaction-路由器以編程方式導(dǎo)航我正在開發(fā)一個應(yīng)用程序,在這個應(yīng)用程序中,我檢查用戶是否不是。loggedIn我必須顯示登錄表單,否則dispatch阿action這將改變路由并加載其他組件。這是我的代碼: render() {
if (isLoggedIn) {
// dispatch an action to change the route
}
// return login component
<Login />
}如何實(shí)現(xiàn)這一點(diǎn),因?yàn)槲也荒茉诔尸F(xiàn)函數(shù)中更改狀態(tài)。
3 回答

米琪卡哇伊
TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個贊
react-router v4
withRouter
history.push
withRouter
Router
import {withRouter} from 'react-router';class App extends React.Component { ... componenDidMount() { // get isLoggedIn from localStorage or API call if (isLoggedIn) { // dispatch an action to change the route this.props.history.push('/home'); } } render() { // return login component return <Login /> }}export default withRouter(App);
重要注記
如果你用 withRouter
若要防止更新被 shouldComponentUpdate
,重要的是 withRouter
包裝實(shí)現(xiàn) shouldComponentUpdate
..例如,在使用Redux時:
/這到處都是 shouldComponentUpdate
withRouter(connect(...)(MyComponent))
/這不是 connect(...)(withRouter(MyComponent))
import {withRouter} from 'react-router';class App extends React.Component { ... render() { if(isLoggedIn) { return <Redirect to="/home"/> } // return login component return <Login /> }}
react-router v2 or react-router v3
context
class App extends React.Component { ... render() { if (isLoggedIn) { // dispatch an action to change the route this.context.router.push('/home'); } // return login component return <Login /> }}App.contextTypes = { router: React.PropTypes.object.isRequired}export default App;
import { browserHistory } from 'react-router';browserHistory.push('/some/path');
添加回答
舉報(bào)
0/150
提交
取消