React 18Alpha - Redux 7.2.4 - redux-thunk 2.3.0 - redux-storage 4.1.2
我在 Redux Store 状态中出现以下错误,似乎减速器正在复制每个节点的状态:
const rootReducer = combineReducers({
serverSettings,
userSettings,
});
我尝试了许多不同的方法来使状态不重复但一切都失败了,reducers 和操作非常简单,它们采用 userSettings 或 serverSettings 对象,该对象对视图中的对象进行了所有更改以更新店铺:
export default function userSettingsReducer(
state: IDefaultState = defaultState,
action: UserSettingsAction
): IDefaultState {
switch (action.type) {
case USER_SETTINGS_SAVE:
return { ...state, userSettings: action.userSettings };
case USER_SETTINGS_LOAD:
return { ...state, userSettings: action.userSettings };
default:
return state;
}
}
操作也很简单:
export const ActionSaveUserSettings =
(userSettings: UserSettings) => (dispatch: Dispatch<UserSettingsAction>) => {
dispatch({ type: USER_SETTINGS_SAVE, userSettings: userSettings });
};
每次分派操作时,我都会将整个 userSettings 对象传递给存储,以保存对对象所做的更改,以使化简器和操作尽可能简单:
const handleOrderSizesChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
dispatch(ActionSaveUserSettings({ ...userSettings, OrderSizes: { ...userSettings.OrderSizes, [e.target.name]: e.target.value } }))
}
这是商店文件:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import { createLogger } from 'redux-logger';
import serverSettings from "./reducers/serverSettingsReducer";
import userSettings from './reducers/userSettingsReducer';
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import { save, load } from "redux-localstorage-simple"
const rootReducer = combineReducers({
serverSettings,
userSettings,
});
const logger = createLogger();
const enhancer = composeWithDevTools(applyMiddleware(save(), thunk, logger));
export const store = createStore(rootReducer, load(), enhancer);
export type RootState = ReturnType<typeof store.getState>
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>()
export default store;
这是默认状态:
export interface IDefaultState {
serverSettings: ServerSettings;
userSettings: UserSettings;
}
更新 - 这解决了问题:
export default function userSettingsReducer(
state: UserSettings = defaultState.userSettings,
action: UserSettingsAction
): UserSettings {
switch (action.type) {
case USER_SETTINGS_SAVE:
return { ...state, ...action.userSettings };
case USER_SETTINGS_LOAD:
return { ...state };
default:
return state;
}
}