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

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

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

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


当前回答

我所做的是在状态之外更新一个值,并执行forceupdate(),由react管理的东西越少越好,因为您可以更好地控制更新的内容。 此外,如果更新速度很快,为每次更新创建一个新数组可能代价太大

其他回答

对于添加到数组中的新元素,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);

如果你在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);
this.setState(preState=>({arrayvar:[...prevState.arrayvar,newelement]}))

这个方法可以解决这个问题。

//------------------code is return in typescript 

const updateMyData1 = (rowIndex:any, columnId:any, value:any) => {

    setItems(old => old.map((row, index) => {
        if (index === rowIndex) {
        return Object.assign(Object.assign({}, old[rowIndex]), { [columnId]: value });
    }
    return row;
}));

如果您正在使用功能组件,请使用如下。

const [chatHistory, setChatHistory] = useState([]); // define the state

const chatHistoryList = [...chatHistory, {'from':'me', 'message':e.target.value}]; // new array need to update
setChatHistory(chatHistoryList); // update the state