2017-05-30 86 views
0

我有幾條路線的設置,像這樣:更改路線陣營路由器的異步操作後

import createHistory from 'history/createMemoryHistory'; 
import { NativeRouter, Route } from 'react-router-native'; 

<NativeRouter history={createHistory()}> 
    <View style={styles.container}> 
    <Route exact path='/' component={Home}/> 
    <Route path='/page1' component={Page1}/> 
    </View> 
</NativeRouter> 

現在是簡單的以編程方式更改航線我Home類,例如:

this.props.history.push('/page1'); 

但在我與終極版派遣一個異步操作的情況下:

export function login(email, password) { 

    return function(dispatch) { 

     dispatch(setAuthBusy(true)); 

     return auth.signIn(email, password) 
     .then(function (user) { 
      dispatch(setAuthBusy(false)); 
      dispatch(setUser(user)); 

      // !CHANGE ROUTE HERE! 

     }) 
     .catch(function (err) { 
      dispatch(setAuthBusy(false)); 
      dispatch(setAuthError(err.message)); 
     }); 
    }; 

} 

在這種情況下,您可以看到它是一個登錄操作,用於對用戶進行身份驗證,並且僅當用戶已成功通過身份驗證時,路由纔會更改爲/page1

我有一種感覺,在異步操作中更改路由不是正確的方式,所以我會很感激一些關於應用程序的一般體系結構和流程的建議。謝謝!

回答

1

如果您開始處理異步操作,則應該查看redux-thunk中間件。

使用redux-thunk你可以做到以下幾點:

class Home extends React.Component { 

    this.onLogin =() => { 
    dispatch(login('toto', 'toto')).then(() => { 
     this.props.history.push('/page1'); 
    }) 
    } 

} 

這意味着,在你的情況下,路線的變化可以通過組件本身進行管理。

希望它有幫助。

+0

感謝您的回覆@Okazari,儘管我已經在上面的示例中使用了redux-thunk。你能否詳細說明你的答案,並且更具體地告訴我如何改變路線? – Tiwaz89

+0

@ Tiwaz89改進這個例子以適合你的用例,這足夠嗎? – Okazari