是否存在用于将动态初始状态的有效负载注入Redux-Toolkit的initialState对象的众所周知的模式?
也就是说,我想这样做-
import initialState from './initialState';
function generateSlice(payload = {}){
const postsSlice = createSlice({
name: 'posts',
initialState: {...initialState, ...payload}, /// inject data here
reducers: {...}
})
}
例如,{availableRooms: []}
是一个空数组,除非在初始化时注入了数据{availableRooms: [{...}]}
此模式不起作用,但是,b / c,我想将动作导出为可调度的,就像这样-
const postsSlice = createSlice({
name: 'posts',
initialState: {...initialState, ...payload},
reducers: {...}
})
export {actionName} from postsSlice.actions;
*****
import {actionName} from '../mySlice'
...
const dispatch = useDispatch();
dispatch(actionName('exampleVal'));
...
我受airbnb
掉毛规则的约束,所以我不能出口let-
let actions; ///Bad
function generateSlice(payload){
const postsSlice = createSlice({
name: 'posts',
initialState: {...initialState, ...payload},
reducers: {...}
})
actions = postsSlict.actions
}
export actions;
如果不使用createSlice
,我追求的功能会更容易一些。我提出这个问题的原因是,我在多个地方看到建议使用createSlice
+ createAction
来代替createReducer
,但是我看不到任何简单的方法来介绍动态数据正在寻找。
我对redux-orm
一无所知,但我认为我追求的功能类似于this SO question
答案 0 :(得分:0)
这是我当前的解决方法,它完全跳过了createSlice
。
在根渲染中
...
const store = initStore(data);
<Provider store={store}>
<App />
</Provider>
还有init函数(为简洁起见,已简化)
import {
configureStore,
getDefaultMiddleware,
combineReducers,
} from '@reduxjs/toolkit';
import reservationReducer from '@reservation/reducer';
import spaceHierarchyReducer from '@map/reducer';
import appStoreReducer from '@app/reducer';
let ReduxStore;
function initStore(
ssrState: Partial<RootStore> = {},
) {
if (ReduxStore) {
return ReduxStore;
}
const slices = {
reservation: reservationReducer,
spaceHierarchy: spaceHierarchyReducer,
appStore: appStoreReducer,
};
const reducer = combineReducers(slices);
const preloadedState = getInitialState(ssrState);
const store = configureStore({
reducer,
middleware,
preloadedState,
});
ReduxStore = store;
initDispatch(store);
return store;
}
在getInitialState
中,我解析URL并根据业务需求设置商店,这是服务器端数据+可以注入URL的参数的组合。然后,在initDispatch
中,我为插入的初始状态的某些初始化逻辑调用store.dispatch()
。
这里使用Typescript很有帮助,因为它可以强制执行getInitialState
返回的数据的形状以及化简器的形状。