【问题标题】:How to return an object array state of Redux reducers如何返回 Redux reducer 的对象数组状态
【发布时间】:2016-09-18 08:47:59
【问题描述】:

有这样的状态:

 review: {
    "amount": 217,
    "snippets": [
      {
       "id": 0,
       "flag": false
      },
      {
       "id": 1,
       "flag": false
      },
      ...
    ]
  }

现在如果我只想设置review.sn-ps[1].flag = true,reducer应该写什么? 例如:

case SET_FLAG: return {
    ...state,
    review: {
      ...state.review,
      snippets: {
        ...state.review.snippets,
        // don't know how to write here to express array
      }
    },
};

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    如果您不使用 combineReducers 来分隔商店的各个部分,您可以保持您的 reducer 情况相似,但对 sn-ps 数组执行类似的操作

    // grab your snippets
    const snippets = state.review.snippets
    
    // create a copy
    const snippetsCopy = snippets.slice()
    
    // replace the element with a new object with the same properties
    // and overwrite the property you want
    snippetsCopy[1] = {
      ...snippetsCopy[1],
      flag: true
    }
    const newSnippetsArray = Object.assign(arr, newArr)
    
    // in your switch case return something like this:
    
    return {
        ...state,
        review: {
          ...state.review,
          snippets: newSnippetsArray
        },
    };
    

    【讨论】:

      猜你喜欢
      • 2017-03-26
      • 1970-01-01
      • 2020-11-10
      • 2019-05-07
      • 1970-01-01
      • 2020-11-01
      • 2021-05-03
      • 2020-03-25
      • 2019-02-03
      相关资源
      最近更新 更多