簡體   English   中英

React Hooks 更新嵌套數組

[英]React Hooks Update Nested Array

我有一個 object 數組,使用 useState 掛鈎在 state 中命名為選項,我只想在特定索引處更新嵌套數組 object。


var subOptionModel = {
        text: "test",
        price: 0,
    };
    var optionModel = {
        optionSetId: 0,
        optionName: "",
        optionPrice: 0,
        editOptionName: false,
        subOptions: [subOptionModel],
    };
    const [options, setOptions] = useState([optionModel]);

我在選項 state 中有多個選項,我如何更新 state,就像索引 2 處的選項和 1 處的子選項一樣,這是我嘗試這樣做的。


setOptions(
                options.map((x, index) => {
                    if (index !== optionIndex) return x;
                    x.subOptions.map((subItem, subIndex) => {
                        console.log(subItem);
                        if (subIndex !== subOptionIndex) return subItem;
                        return {
                            ...subItem,
                            text: text
                        };
                    });
                }),
            );

我建議您使用不可變庫,例如immer.js 這將允許您精確地在 state 中更新您想要更新的 select。

這將允許您像這樣修改您的選項:

import produce from "immer"

const newOptions = produce(options, draftOptions => {
    draftOptions[2].subOption[1] = [whatever you want]
})

setOptions(newOptions)

對於這種數據 model,我寧願使用,useReducer 鈎子。 就個人而言,我覺得它更干凈。

但你的問題是,你沒有變異並返回你的 subOptions 。

setOptions(
  options.map((x, index) => {
      if (index !== optionIndex) return x;
      x.subOptions = x.subOptions.map((subItem, subIndex) => {
          console.log(subItem);
          if (subIndex !== subOptionIndex) return subItem;
          return {
              ...subItem,
              text: text
          };
      });

      return x;
  }),
);

按照您的解決方案,如果index === optionIndex ,您錯過了在第一個map中返回。

setOptions((options) => {
  return options.map((x, index) => {
    if (index !== optionIndex) return x;
    return {
      ...x,
      subOptions: x.subOptions.map((subItem, subIndex) => {
        if (subIndex !== subOptionIndex) return subItem;
        return {
          ...subItem,
          text: text
        };
      })
    }
  })
})

否則你可以使用類似immer.js

暫無
暫無

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

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