【问题标题】:Store.Dispatch() Resetting Redux StoreStore.Dispatch() 重置 Redux 存储
【发布时间】:2021-12-16 15:47:48
【问题描述】:

我dispatch(action()) 从我的反应组件外部触发action。它工作正常,因为它正在触发我的操作并更新我的store 中的新项目。问题是它似乎完全重置了我的store 中的所有其他内容,这至少对我来说是个问题而不是其价值。

值得注意的是:我使用的是next.js。

这是我的流程的基本概念:

我有一个 utils 文件夹,其中包含一个服务,我将从以下位置发送此操作:

import store from './store';
store.dispatch(myAction());

我有我的行动

export const myAction = () => ({
  type: HELP_ME,
  payload: true,
});

const initialState = {
  reducerVar: fase,
  otherExistingVar: {},
  otherExistingVarTwo: null,
  otherExistingThree:null,
  otherExistingVarFour: false,
};

const myReducer = (state = initialState, action) => {
  switch (action.type) {
    case HELP_ME: {
      const reducerVar = action.payload;
    } 
    default: {
      return state;
    }
  }
};
export default myReducer;

我不确定我是否在滥用store.dispatch(),因为如果它完全清除了存储中的现有数据,我不明白为什么有人会使用这种技术。或者有没有更好的方法从我的组件外部触发这个简单的动作。

基本上,我想dispatch 这个动作,而不是完全清除我的商店,就像我在组件中调度动作一样。

谢谢!

【问题讨论】:

  • 你的减速器是什么样子的?商店是什么样子的?

标签: javascript reactjs redux react-redux redux-thunk


【解决方案1】:

你应该像这样在reducer中返回带有值的状态。

const myReducer = (state = initialState, action) => {
  switch (action.type) {
    case HELP_ME: {
      return {...state, reducerVar : action.payload}
    } 
    default: {
      return state;
    }
  }
};

【讨论】:

    【解决方案2】:

    您正在尝试做的事情很好。但是您的 reducer 必须通过如下操作完成更改并返回整个状态。

    const myReducer = (state = initialState, action) => {
      switch (action.type) {
        case HELP_ME:
          const reducerVar = action.payload;
          return {...state, reducerVar }
        default:
          return state;
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 2023-03-04
      • 2020-03-29
      • 1970-01-01
      相关资源
      最近更新 更多