亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用Reaction-路由器以編程方式導航

使用Reaction-路由器以編程方式導航

郎朗坤 2019-06-09 15:32:20
使用Reaction-路由器以編程方式導航我正在開發一個應用程序,在這個應用程序中,我檢查用戶是否不是。loggedIn我必須顯示登錄表單,否則dispatch阿action這將改變路由并加載其他組件。這是我的代碼:    render() {          if (isLoggedIn) {              // dispatch an action to change the route          }          // return login component          <Login />     }如何實現這一點,因為我不能在呈現函數中更改狀態。
查看完整描述

3 回答

?
米琪卡哇伊

TA貢獻1998條經驗 獲得超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包裝實現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');


查看完整回答
反對 回復 2019-06-09
  • 3 回答
  • 0 關注
  • 623 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號