我想在状态数组的末尾添加一个元素,这是正确的方法吗?
this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });
我担心用push修改数组可能会导致麻烦——它安全吗?
另一种方法是复制数组,setstate看起来很浪费。
我想在状态数组的末尾添加一个元素,这是正确的方法吗?
this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });
我担心用push修改数组可能会导致麻烦——它安全吗?
另一种方法是复制数组,setstate看起来很浪费。
当前回答
ES6最简单的方法:
this.setState(prevState => ({
array: [...prevState.array, newElement]
}))
其他回答
我试图在数组状态下推值,并像这样设置值,并通过映射函数定义状态数组和推值。
this.state = {
createJob: [],
totalAmount:Number=0
}
your_API_JSON_Array.map((_) => {
this.setState({totalAmount:this.state.totalAmount += _.your_API_JSON.price})
this.state.createJob.push({ id: _._id, price: _.your_API_JSON.price })
return this.setState({createJob: this.state.createJob})
})
如果使用ES6,这是最简单的方法。
initialArray = [1, 2, 3];
newArray = [ ...initialArray, 4 ]; // --> [1,2,3,4]
新数组为[1,2,3,4]
在React中更新你的状态
this.setState({
arrayvar:[...this.state.arrayvar, newelement]
});
了解关于数组解构的更多信息
//get the value you want to add
const valor1 = event.target.elements.valor1.value;
//add in object
const todo = {
valor1,
}
//now you just push the new value into the state
//prevlista is the value of the old array before updating, it takes the old array value makes a copy and adds a new value
setValor(prevLista =>{
return prevLista.concat(todo) })
目前很多人都面临着更新useState钩子状态的问题。我使用这种方法来安全地更新它,并想在这里分享它。
这就是我的状态
const [state, setState] = useState([])
假设我有一个对象名为obj1,我想把它附加到我的状态中。我建议这样做
setState(prevState => [...prevState, obj1])
这将安全地在末尾插入对象,并保持状态一致性
当我想修改数组状态时,我也遇到了类似的问题 同时保留元素在数组中的位置
这是一个在like和different之间切换的函数:
const liker = (index) =>
setData((prevState) => {
prevState[index].like = !prevState[index].like;
return [...prevState];
});
正如我们所说,函数接受数组状态元素的索引,然后我们继续修改旧状态并重建状态树