如何在 redux 状态下访问数组(对象)元素 [英] How to access array (object) elements in redux state

查看:69
本文介绍了如何在 redux 状态下访问数组(对象)元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 React/Redux,我有一个简单的 React 游戏,其中用户响应来自多个选项的提示,我想记录响应以及它是否正确.我有一个 'GAME_BEGIN' 减速器,比如

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

现在我想将 responseisCorrect 属性添加到操作 'GAME_SUBMIT_RESPONSE' 的第一个问题对象,然后添加一个新问题到问题数组.所以经过几次迭代(可能有很多问题),我认为状态应该看起来像

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

对于第一个问题,我可能会通过重写整个 problems 数组来添加属性,但是一旦添加新对象呢?

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

或者我是否以错误的方式思考这个问题.我还认为我可以拉平状态并完全摆脱 problems 数组,在每次提交时重置问题,并通过 api 调用将必要的数据登录到数据库.这是预期的做事方式吗?

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?

推荐答案

先复制你的状态怎么样

let newState = {...state};

然后你像任何其他 JS 对象一样更新元素/值之一

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

newState.problems[2].response = 42;

那你退货了吗?

return newState;

reducer 只是一个函数,你不必马上返回.单行并非不可能,但可能不可读(sliceconcat、...).

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, ...).

这篇关于如何在 redux 状态下访问数组(对象)元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆