我想在状态数组的末尾添加一个元素,这是正确的方法吗?

this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });

我担心用push修改数组可能会导致麻烦——它安全吗?

另一种方法是复制数组,setstate看起来很浪费。


当前回答

这对我来说很有用,可以在数组中添加一个数组

this.setState(prevState => ({
    component: prevState.component.concat(new Array(['new', 'new']))
}));

其他回答

这对我来说很有用,可以在数组中添加一个数组

this.setState(prevState => ({
    component: prevState.component.concat(new Array(['new', 'new']))
}));

React文档说:

对待这个问题。状态,仿佛它是不可变的。

您的推送将直接改变状态,这可能会导致容易出错的代码,即使您随后再次“重置”状态。例如,它可能导致一些生命周期方法(如componentDidUpdate)无法触发。

在以后的React版本中,推荐的方法是在修改状态时使用updater函数来防止竞争条件:

this.setState(prevState => ({
  arrayvar: [...prevState.arrayvar, newelement]
}))

与使用非标准状态修改可能面临的错误相比,内存“浪费”不是一个问题。

早期React版本的替代语法

你可以使用concat来获得一个干净的语法,因为它返回一个新数组:

this.setState({ 
  arrayvar: this.state.arrayvar.concat([newelement])
})

在ES6中,你可以使用扩展操作符:

this.setState({
  arrayvar: [...this.state.arrayvar, newelement]
})
this.setState((prevState) => {   
    const newArray = [...prevState.array];   
    newArray[index] = updatedValue;   
    return { array: newArray };   
});

如果你在React中使用功能组件

const [cars, setCars] = useState([{
  name: 'Audi',
  type: 'sedan'
}, {
  name: 'BMW',
  type: 'sedan'
}])

...

const newCar = {
  name: 'Benz',
  type: 'sedan'
}

const updatedCarsArray = [...cars, newCar];

setCars(updatedCarsArray);

对于添加到数组中的新元素,push()应该是答案。

对于删除元素和更新数组的状态,下面的代码适用于我。拼接(索引,1)不能工作。

const [arrayState, setArrayState] = React.useState<any[]>([]);
...

// index is the index for the element you want to remove
const newArrayState = arrayState.filter((value, theIndex) => {return index !== theIndex});
setArrayState(newArrayState);