【问题标题】:Is this the correct way to update a propery in objects array state这是更新对象数组状态中的属性的正确方法吗
【发布时间】:2023-01-03 04:03:42
【问题描述】:

我有下面的代码,我想更新 ID 为 1 的对象中的名称属性。我正在使用代码 objArray[1].name = "Xxx" 进行更新。它完美地工作,但这是正确的吗?我应该将 prevState 与 setObjArray 一起使用吗?你觉得这看起来容易多了?

const [objArray, setObjArray] = useState([
    {
            id:1,
            name:"Eren"
    },
    {
            id:2,
            name:"Eren2"
    },
    {
            id:3,
            name:"Eren3"
    }

])

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    有很多方法可以做到这一点。让我分享一种方法来做到这一点:

    1. 制作数组的浅拷贝
      let temp_state = [...objArray]; 
      
      1. 对要改变的元素进行浅表复制
      let temp_element = { ...temp_state[0] };
      
      1. 更新您感兴趣的属性
      temp_element.name = "new name";
      
      1. 将它放回我们的数组中。注意我们在这里改变数组,但这就是我们首先制作副本的原因
      temp_state[0] = temp_element;
      
      1. 将状态设置为我们的新副本
      setObjArray(temp_state);
      

    【讨论】:

      【解决方案2】:

      不,这是不可取的。您有用于更新状态的 useState 第二个数组元素 (setObjArray)。阅读 React useState 的文档。有两种基本方法,但没有太大区别。第一种方法;

        const changeName = (id, newName) => {
          // map through the array and change the name of the element with the id you are targeting
          const changedArr = objArray.map((element) => {
            if (element.id === id) {
              return {
                ...element,
                name: newName,
              };
            } else {
              return element;
            }
          });
          // set the returned array as you new state 
          setObjArray(changedArr)
        };
      

      第二种方法;

      • 您可以访问以前的状态。这样您就可以对以前的状态进行更改并将新数组作为新状态返回。
       const newChangeName = (id, newName) => {
          setObjArray((prev) => {
            // map through the array and change the name of the element with the id you are targeting
            // set the returned array as you new state
            return prev.map((element) => {
              if (element.id === id) {
                return {
                  ...element,
                  name: newName,
                };
              } else {
                return element;
              }
            });
          });
        };
      
      

      希望这有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-01
        • 2021-11-10
        • 1970-01-01
        • 1970-01-01
        • 2019-04-28
        • 2021-09-14
        相关资源
        最近更新 更多