簡體   English   中英

如何在 Reactjs 中使用 useState 更新嵌套的 object 數組?

[英]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,
    });

但一切都錯了。

問題是如何更新嵌套字段中的值,例如更新對象數組中 object 中的字段。

可以使用一些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;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM