当Reducer字段为空时部署操作

时间:2017-01-19 17:57:47

标签: reactjs redux

我们说我有一个auth reducer,它保存有关当前用户的信息。当auth reducer为null时,自动部署populateUser()操作的最佳方法是什么,但我在本地存储中有一个有效的jwt?

1 个答案:

答案 0 :(得分:1)

如果你正在使用React-Router,你可以使用" onEnter" hook用于向后端路由发送ajax请求,该路由每次发生路由更改时都会检查令牌的请求标头。然后,服务器发回相关的用户数据,这允许更新状态。以下代码假定对api请求使用react-redux,redux-thunk中间件和axios。



<Provider store={store}>
    <Router history={browserHistory}>
      <Route path="/" component={App} onEnter={checkAuth }>      
        < children..../>
    </Route>
  </Router>
</Provider>
      
function checkAuth(){
  store.dispatch(authenticate())   
}     

function authenticate() {
  return function (dispatch) {
     axios.get('/api/auth/')
     .then(user => {
         dispatch(populateUser(user))
       }
    }
 }
&#13;
&#13;
&#13;