首页 > 解决方案 > useEffect 重写整个商店

问题描述

我有一个带有 3 个减速器的 redux 商店:

let reducers = combineReducers({
config: configReducer,
data: dataReducer,
currentState: gameStateRecuder})

let store = createStore(reducers, applyMiddleware(thunkMiddleware));

在这些减速器中的每一个中,初始存储都是空的,但是一旦安装了 App 组件,我就会用我收到的使用 usinguseEffect来替换减速器内的每个初始存储。在每个 reducer 中都是这样的:axios.getredux-thunk

let initialState = [];

const SET_STATE = 'SET_STATE';

const configReducer = (state = initialState, action) => {

    switch (action.type) {
        case SET_STATE: {
            return { ...action.state};
        }
        default:
            return state;
    }

const setState = (state) => ({ type: SET_STATE, state });

export const getConfigState = () => (dispatch) => {
    getAPI.getConfig() //I import getAPI with all the REST API logic//
    .then(response => {
        dispatch(setState(response));
    })
};

App 触发器是:

const App = (props) => {
  useEffect(() => {
    props.getConfigState();
    props.getDataState();
    props.getGameState();
  }, []);
  return (
   //JSX//
  );
}

export default compose(connect(null, { getConfigState, getDataState, getGameState }))(App);

但是,当应用程序安装时,我遇到了这个混乱:每个操作的控制台日志

最后,我将每个 reducer 的状态替换为 promise 解决了最后一个的状态。我可以尝试使用 HOC 将应用程序再包装 2 次,该 HOC 除了重写精确减速器的状态外,什么都不做,但我仍然想了解是什么导致承诺影响除了他需要影响的其他减速器之外的其他减速器。

标签: javascriptreactjsreduxreact-hooksredux-thunk

解决方案


一个愚蠢的错误,但也许有人有完全相同的问题 - 解决方案是为每个减速器提供不同的案例名称 -SET_STATE需要分别成为SET_GAME_STATE, 。我相信这是因为我对工作原理的误解。SET_CONFIG_STATESET_DATA_STATEdispatch


推荐阅读