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

IT技术 javascript reactjs redux
2021-05-14 06:24:48

我正在使用带有 reactjs 的 redux。

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

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

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

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

    default:
      return state
  }
}
3个回答

这对我有用:

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

你只是有几个错误{}而不是[]忘记使用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;

这可能有效

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;