How to access array (object) elements in redux sta

2019-07-26 08:42发布

问题:

Using React/Redux, I have a simple react game where a user responds to a prompt from a number of choices, I want to log the response and whether it is correct. I have a 'GAME_BEGIN' reducer like

case 'GAME_BEGIN':
  return {
    ...state,
    timeRemaining: action.timeRemaining,
    gameIsInProgress: true,
    problems: [
      {
        problem: action.problem, // string
        solution: action.solution, // string
        incorrectResponses: action.incorrectResponses, // array of strings
      }
    ]
  };

And now I want to add response and isCorrect attributes to the first problem object on action 'GAME_SUBMIT_RESPONSE', then add a new problem to the problems array. So after a few iterations (there can be many problems), I was thinking state should look like

...state,
problems: [
  {
    problem: something, // string
    solution: something, // string
    incorrectResponses: something, // array of strings
    response: something,
    isCorrect: somethingBool
  },
  ...
  {
    problem: action.problem, // string
    solution: action.solution, // string
    incorrectResponses: action.incorrectResponses, // array of strings
  }
]

For the first problem I might add attributes by just rewriting the entire problems array, but how about once I add new objects?

Or am I thinking about this in the wrong way. I also thought I could flatten out the state and get rid of the problems array altogether, resetting the problem on each submit and loggin the necessary data to the DB via api call. Is this the intended way of doing things?

回答1:

What about copying your state first

let newState = {...state};

then you update one of the elements/values like any other JS object

newState.problems[2].response = 42;

then you return it?

return newState;

A reducer is just a function, you don't have to return right away. A one-liner is not impossible, but likely unreadable (slice, concat, ...).



标签: reactjs redux