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

时间:2016-02-15 07:52:07

标签: 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
  }
}

3 个答案:

答案 0 :(得分:5)

您在使用{}而非[]而忘记使用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;

它也可能有助于看到它以这种方式表达。它做了同样的事情,但我认为它看起来更好一点

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;

或者如果你正在使用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;

答案 1 :(得分:2)

这对我有用:

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

答案 2 :(得分:1)

这可能有用

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

export default reducer;