本文介绍了redux - 如何存储和更新键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 redux 和 reactjs.

I am using redux wth reactjs.

我想存储简单的键/值对,但无法正确使用 reducer 语法.

I want to store simple key/value pairs but can't get the reducer syntax right.

在这种情况下,每个键/值对都将保持与外部系统的连接.

In this case each key/value pair will hold a connection to an external system.

这是正确的做法吗?我刚开始使用 redux,所以有点神秘.

Is this the right way to do it? I'm at the beginning with redux so it's a bit of mystery.

export default (state = {}, action) => {
  switch(action.type) {
    case 'addConnection':
      return    {
        connections: {
          ...state.connections, {
          action.compositeKey: action.connection
        }
      }

    default:
      return state
  }
}

推荐答案

这对我有用:

export default (state = {}, action) => {
  switch(action.type) {
    case 'addConnection':
      return {
        ...state,
        connections: {
          ...state.connections,
          [action.compositeKey]: action.connection
        }
      }
    default:
      return state
  }
}

来自文档:

https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#correct-approach-copying-all-levels-of-nested-data

这篇关于redux - 如何存储和更新键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 15:26