如何在 Reactjs 中使用 useState 更新具有数组的嵌套对象?

How to update nested object having array with useState in Reactjs?

你好开发者你好吗?

我正在尝试更新嵌套值,但都失败了。

const [ControlGaps, setControlGaps] = useState([
    {
      id: 1,
      name: "Pizza 1",
      status: 1,
      applicable: true,
      questions: [
        {
          id: 1,
          question:
            "how are you?",
          answer: null,
          evidence: null,
          treatment: null,
          type: "Implemented",
        {
          id: 2,
          evidence: null,
          treatment: null,
          type: "Implemented",
          question:
            "how old are you?",
          answer: null,
         }
      ],
    },
    {
      id: 2,
      name: "Pizza 2",
      status: 1,
      applicable: true,
      questions: [
        {
          id: 1,
          type: "Implemented",

          question:
            "How are you 2?",
          answer: null,
          evidence: null,
          treatment: null,
         
        {
          id: 2,
          answer: null,
          evidence: null,
          treatment: null,
          type: "Implemented",
          question:
            "How old are you?",
        },
      ],
    }])

我尝试使用 onChange 这个

    setControlGaps([...ControlGaps, [ControlGaps[index]].applicable]:checked]);

    setControlGaps({
      ...ControlGaps,
      [ControlGaps[index].applicable]: checked,
    });

但是都错了

问题是如何更新嵌套字段中的值 例如更新对象数组中对象中的字段。

可以使用一些 slice()spread 来完成。但是你应该看看这种嵌套的东西的不变性助手。

setControlGaps([setControlGaps.slice(0,index),
{ ...ControlGaps[index],
 applicable : checked
}
,setControlGaps.slice(index+1)]);

试试这个

setControlGaps(prevState => {
    const newState = prevState.map((item, itemIndex) => {
        if (itemIndex === index) {
            item.applicable = false;
            return item;
        }
        return item;
    });
    return newState;
});