我有一个具有不同访问级别的应用,例如admin,guest和普通用户,因此它具有多个角色。我的文件夹结构非常清晰,某些组件是共享的,例如Button,Loader,但是reduces和action不共享,因为它们与应用程序完全不同。
我这样做是为了对商店进行条件设置(是的,我只需要一个商店,因为所有类型的用户的输入都相同)
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { getUserRole } from './utils' // merely localstorage util to get roles
import { composeWithDevTools } from 'redux-devtools-extension'
import userReducers from './reducers'
import adminReducers from './reducers/admin'
//share reducer btw member and admin
let reducers
if (getUserRole() === 'member') {
reducers = userReducers
} else {
reducers = adminReducers
}
console.log('reducers', reducers) //undefined during the first load, most likely store is done setup before localstorage?
const store = createStore(
reducers,
composeWithDevTools(
applyMiddleware(thunk)
)
)
export default store
问题在于,除非我刷新整个页面,否则减速器为undefined
。
答案 0 :(得分:1)
也许是因为this SO answer,localStore
并不异步。
因此,通过返回Promise
,您将确保getUserRole()
不是undefined
:
export function getUserRole(){
return new Promise((resolve, reject) => {
let role = localStorage.getItem('token').decode('role')
resolve(role)
})
}
和index.js
中的
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { getUserRole } from './utils' // merely localstorage util to get roles
import { composeWithDevTools } from 'redux-devtools-extension'
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
如果出现问题请告诉我。