在 React JS 中将值数组附加到状态中的当前数组

Append array of values to the current array in a state in React JS

我的状态值为

this.state = {
    emp: [
        {id: "1", name: "A"}
        {id: "2", name: "B"}
        {id: "3", name: "B"}
    ]
}

如何在不删除数组当前值的情况下将 var arr = {id:"4", name:"D"} 这样的数组添加到状态 emp。我只想将新的值数组附加到当前状态数组。有人可以帮忙吗?

只需使用concat

this.setState({ emp: this.state.emp.concat('new value') })

concat 优于 pushunshift 的原因是

Array.push

Array.prototype.push allows us to push elements to the end of an array. This method does not return a new copy, rather mutates the original array by adding a new element and returns the new length property of the object upon which the method was called.

Array.unshift

To add elements to the very beginning of an array. Just as push, unshift does not return a new copy of the modified array, rather the new length of the array

这两种方式都会改变array的突变状态。一个突变术语应该保持不变,因为它是我们的原始来源。

array.concat

concat()方法用于合并两个或多个数组。此方法不会更改现有数组,而是 returns 一个新数组。

但是,您 Object.assign() 也创建了分配给它的对象的深层副本。

let emp = Object.assign([],this.state.emp); //type of an array

结果

在现代 JavaScript 中,您可以使用扩展运算符:

添加单个项目

addItem = item => {
  this.setState({
    emp: [
      ...this.state.emp,
      item 
    ]
  })
}

添加多项:

addItems = items => {
  this.setState({
    emp: [
      ...this.state.emp,
      ...items
    ]
  })
}

spread operatorthis.state.emp 中的所有元素放入一个新的数组实例中,item 作为最后一个元素附加。

您不应使用 setState 以外的其他方式改变组件的状态,因为您的渲染数据会不同步。

如果使用函数式 setState(因为您是基于 prevState 更新状态)和扩展语法,则需要更新

this.setState(prevState => ({
    emp: [
        ...prevState.emp, 
        {id:"4",name:"c"}
    ]
}))

如果使用功能组件,瞧一个简单的例子:

const [hiddenDivs, setHiddenDivs] = useState([1, 2, 3, 4]);

const handleCatDivTitleClick = (divNum: number) => {
   if (hiddenDivs.includes(divNum)) {
      setHiddenDivs(hiddenDivs.filter((d) => d !== divNum));  //REMOVE FROM ARRAY
   } else {
      setHiddenDivs([...hiddenDivs, divNum]);  //ADD TO ARRAY
   }
};

<div class={`${style.catDiv} ${hiddenDivs.includes(1) ? style.catDivHide : ''}`}>
   <div class={style.catTitle} onClick={() => handleCatDivTitleClick(1)}>
      Imagine a list of categories like this. All begin "hidden" (shrunk-up).
   </div>
</div>
<div class={`${style.catDiv} ${hiddenDivs.includes(2) ? style.catDivHide : ''}`}>
   <div class={style.catTitle} onClick={() => handleCatDivTitleClick(2)}>
       You want to shrink/expand category based on clicking title.
   </div>
</div>
<div class={`${style.catDiv} ${hiddenDivs.includes(3) ? style.catDivHide : ''}`}>
   <div class={style.catTitle} onClick={() => handleCatDivTitleClick(3)}>
      Basically, a home-rolled accordian-type display.
   </div>
</div>