首页 文章

清洁Redux State

提问于
浏览
2

在开始之前,我澄清一下,在我提出这个问题之前我已经阅读了很多,甚至How to reset the state of a Redux store?,说,我们走吧 .

我正在使用React和Redux时,通常当我创建一个状态时,我不使用void new对象作为初始状态,而是 Build 一个结构化初始状态,例如:

const initialState = {
  objectWithSomething: null,
  array: [],
  someString: ''
}
const someReducer = (state=initialState, action) => {
   switch(action.type) {
     case 'meh':
       // do something
       return { ...state, someString: ... }
   }
}

通常,当我想要清理状态时,只需要返回vanilla initialState并且's all, but this case is different, for some reason that I don' t了解状态是否被部分清理,就像......只是重置了一些裸项,但是数组,对象和其他一些嵌套项目都不是't cleaned, which is very weird, if i compare the state (inside the reducer) vs the initialState (the constant) they are the same, in some point maybe I' m改变国家或某事?我不知道,但让我展示我的结构:

Note :这是一个要点,因为它是一个大而重复的文件(是一个测试,我试图在任何优化之前做出某种新的方法) .

reducer.js initialState.js

好吧,即使采用丹·阿布拉莫夫在上述问题中暴露的方法,国家也不能很好地清理,这是清理后的状态(返回initialState或使用Abramov方法):

newState.js

任何人都可以给我一些线索,想法或什么?

1 回答

  • 1

    根据我的理解,你在多个地方改变状态:

    例:

    if (action.type === errors.GENERAL) {
        const errorsState = state.errors //errorState is a reference
        errorsState.general = action.payload //you mutate a property inside of it
        return { ...state, errors: errorsState } //and return the reference itself
    }
    

    相反,你应该:

    if (action.type === errors.GENERAL) {
      const newErrorsState = {...state.errors, general: action.payload}
      return { ...state, errors: newErrorState }
    }
    

相关问题