Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在给定键时,从对象数组更改对象值的最佳方法_Javascript_Reactjs - Fatal编程技术网

Javascript 在给定键时,从对象数组更改对象值的最佳方法

Javascript 在给定键时,从对象数组更改对象值的最佳方法,javascript,reactjs,Javascript,Reactjs,我在学校工作(学习)。我有一个包含玩家代号信息的对象数组。它们的评级最高为五星,当用户单击GUI中的星星以更改评级时,将调用此函数 我的解决方案: 我复制一个state,在副本上迭代,检查每个条目的键,重新分配星号,然后使用我的setState钩子分配修改过的数组 有没有更简洁的方法?我搜索了stack和google,什么也没找到。我觉得我应该能够映射,使用箭头函数和/或三元函数。感谢大家对样式的评论,JS和ES6似乎都是这样。Thx-fam function changeStars(sta

我在学校工作(学习)。我有一个包含玩家代号信息的对象数组。它们的评级最高为五星,当用户单击GUI中的星星以更改评级时,将调用此函数

我的解决方案: 我复制一个state,在副本上迭代,检查每个条目的键,重新分配星号,然后使用我的setState钩子分配修改过的数组

有没有更简洁的方法?我搜索了stack和google,什么也没找到。我觉得我应该能够映射,使用箭头函数和/或三元函数。感谢大家对样式的评论,JS和ES6似乎都是这样。Thx-fam

  function changeStars(stars, key) {
    console.log(stars, key);
    const newRatingInventory = [ ...tagInventory];

    for (const [index] of newRatingInventory.entries()) {
      if (newRatingInventory[index].timeStamp === key) {
        newRatingInventory[index].stars = stars;
      }
    }
    setTagInventory([...newRatingInventory]);

使用spread语法不会创建深度副本—它只是创建一个新数组,但不会克隆对象。因此,对新数组中的任何对象所做的任何更改都将改变原始对象

目前,您正在直接改变状态,这不是React中更新状态的正确方法

如果条件
newRatingInventory[index].timeStamp==key
的计算结果为true,则应使用
.map()
方法迭代数组,创建并返回一个新对象

function changeStars(stars, key) {
    const newState = tagInventory.map(obj => {
       if (obj.timeStamp === key) { 
          // return a new object with the updated 
          // value of "stars" property.
          return { ...obj, stars };
       }
       
       // if the above condition is not true,
       // return the current object as it is.
       return obj;
    });
   
    // update the state
    setTagInventory(newState);
}

有多种方法可以做到这一点

我的推荐是地图

const changeStars = (stars, key) => {
let tempRating = tagInventory && tagInventory.length > 0 && 
    tagInventory.map(item => item.timeStamp === key ? {...item, stars} : item);
 setTagInventory(tempRating)
}

像冠军一样工作。thx,我没有意识到这不是一个深度拷贝,我在谷歌上搜索了一下,发现spread操作符在一个数组上只能进行1级深度,所以就像你说的,对象本身是浅的,不是克隆。很高兴我问了,这是非常有帮助的知道。谢谢你