You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Reducer中向嵌套的answers数组添加对象?

给指定问题添加新答案的函数实现

因为状态通常需要保持不可变性(比如在Redux这类状态管理场景中),下面是符合要求的函数实现:

依赖说明

先确保你已经安装并导入了uuid库来生成唯一ID:

import { v4 as uuidv4 } from 'uuid';

通用实现(指定问题ID添加)

这个函数可以给任意ID匹配的问题添加新答案:

const addAnswerToQuestion = (state, targetQuestionId) => {
  // 生成新的答案对象
  const newAnswer = { answerid: uuidv4() };

  // 返回全新的状态副本,不修改原状态
  return {
    ...state,
    questions: state.questions.map(question => {
      if (question.id === targetQuestionId) {
        return {
          ...question,
          answers: [...question.answers, newAnswer]
        };
      }
      return question;
    })
  };
};

简化实现(给第一个问题添加)

如果只需要给数组中的第一个问题添加答案,可以用这个更简洁的版本:

const addAnswerToFirstQuestion = (state) => {
  if (!state.questions.length) return state;

  const newAnswer = { answerid: uuidv4() };
  return {
    ...state,
    questions: [
      {
        ...state.questions[0],
        answers: [...state.questions[0].answers, newAnswer]
      },
      ...state.questions.slice(1)
    ]
  };
};

使用示例

// 假设initState是你提供的初始状态
const newState = addAnswerToQuestion(initState, initState.questions[0].id);
// 或者用简化版
const newState = addAnswerToFirstQuestion(initState);

内容的提问来源于stack exchange,提问作者abdul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:40:27