【问题标题】:Deploy Action when Reducer Field is Null当 Reducer 字段为 Null 时部署操作
【发布时间】:2017-01-19 17:57:46
【问题描述】:

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

【问题讨论】:

  • the auth reducer is null 是什么意思?您的意思是 auth reducer 中的当前用户为 null 吗?
  • 很抱歉给您带来了困惑。是的,我就是这个意思。
  • 你真的需要随时执行这个动作吗?页面加载够了还没有执行?
  • 我想我真正想要的是每当路线改变时。
  • 你能编辑你的答案吗?添加更多细节(您使用的是 react-router 吗?)和关键部分的源代码。

标签: reactjs redux


【解决方案1】:

如果您使用 React-Router,您可以使用“onEnter”钩子将 ajax 请求发送到后端路由,该路由会在每次路由更改时检查请求标头中的令牌。然后服务器发回相关的用户数据,允许更新状态。以下代码假设使用 react-redux、redux-thunk 中间件和 axios 来处理 api 请求。

<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))
       }
    }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 2018-05-29
    • 2016-07-03
    相关资源
    最近更新 更多