redux - 如何存储和更新键/值对

Duk*_*gal 7 javascript reactjs redux

我正在使用redux wth reactjs.

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

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

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

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

    default:
      return state
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 10

这对我有用:

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

从文档:

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


Tha*_*you 6

你只是犯了一些错误{}而不是[]忘记使用Object.assign.

const reducer = (state = {}, action) => {
  switch (action.type) {
    case 'addConnection':
      return Object.assign({}, state, {
        connections: [
           ...state.connections,
           {
             [actions.compositeKey]: action.connection
           }
        ]
      });
    default:
      return state;
  }
}

export default reducer;
Run Code Online (Sandbox Code Playgroud)

看来它也表达了这种方式可能会有所帮助.它做同样的事情,但我认为它看起来更好一点

const reducer = (state = {}, {type, compositeKey, connection}) => {
  switch (type) {
    case 'addConnection':
      return Object.assign({}, state, {
        connections: state.connections.concat({
          [compositeKey]: connection
        })
      });
    default:
      return state;
  }
}

export default reducer;
Run Code Online (Sandbox Code Playgroud)

或者,如果你使用的是Immutable,就像这样

import Immutable from 'immutable';

const reducer = (state = Immutable.Map(), {type, compositeKey, connection}) => {
  switch (type) {
    case 'addConnection':
      return state.set(
        'connections',
        state.get('connections').concat({
          [compositeKey]: connection
        })
      );
    default:
      return state;
  }
}

export default reducer;
Run Code Online (Sandbox Code Playgroud)