redux - how to store and update a key/value pair

2019-04-28 05:22发布

问题:

I am using redux wth reactjs.

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.

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
  }
}

回答1:

You just have a couple mistakes with {} instead of [] and forgetting to use 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;

It might help to see it expressed this way too. It does the same thing but I think it reads a little nicer

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;

Or if you're using Immutable, something like this

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;


回答2:

This worked for me:

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

From the docs:

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



回答3:

This may work

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;