2017-05-30 63 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