在异步函数中执行createStore时未定义存储区吗?

时间:2018-08-11 13:53:23

标签: javascript reactjs redux

在redux商店中,是否可以将一组不同的reducer加载到一个商店中?我的尝试失败了

import userReducers from './reducers'
import adminReducers from './reducers/admin'

//share reducer btw member and admin
let store
getUserRole().then(role => {
   reducers =  role === 'member'
   ? userReducers
   : adminReducers
   console.log('reducers', reducers) 
   store =  createStore(
       reducers,
       composeWithDevTools(
           applyMiddleware(thunk)
       )
   )
})

export default store

我还创建了一个缩影来演示问题。

https://codesandbox.io/s/n5r445nnom

1 个答案:

答案 0 :(得分:2)

请仔细阅读此答案

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

因此,then函数中的代码基本上是在undefined store导出并在其他文件中使用后运行的

要对此进行检查,您还可以添加一个console.log,然后在设置存储后起作用