当我有多个reducer时如何重置仅一个reducer的状态,并防止在只有一个reducer的状态重置时重新加载

时间:2019-07-14 10:59:59

标签: javascript reactjs react-redux reducers

我将用户以表单形式输入的数据保持在化简器的状态。我还有另一个化简器,其状态与某些其他功能相关。现在,我有一个表单重置按钮,单击该按钮,我想要更新状态仅是formReducer而不是其他reducer的状态。我也不希望我的应用在formReducer的状态重置时重新加载

已经添加了我用来实现功能的代码段,但是发生的是,整个应用程序在单击重置时重新加载,并且两个reducer的状态最终都被重置了 我的index.js具有以下代码

   const appReducers = combineReducers({
       r1: reducer1, 
       formSubmissionReducer: formSubmissionReducer
       });
   const rootReducer = (state, action) => {

      if (action.type === "RESET_FORM") {
        const { r1 } = state;
        console.log(r1);
        state = { r1};

        }

      return appReducers(state, action);
    };

1 个答案:

答案 0 :(得分:0)

您必须将减速器分开,现在,当您执行RESET_FORM操作时,只需 formSubmissionReducer将对此作出反应,reducer1将仅返回状态。 阅读redux docs,他们的解释比我更好。

const reducer1 = (state, action) => {

      ... // swtich statment
      return state;
    };
    
    const formSubmissionReducer = (state, action) => {

      if (action.type === "RESET_FORM") {
        // it will update the form variable inside the `formSubmissionReducer` state
        return state = {...state, form: action.payload};
      }

      return state;
    };
    
    
   const rootReducer = combineReducers({
       r1: reducer1, 
       formSubmissionReducer: formSubmissionReducer
   });