我想在状态数组的末尾添加一个元素,这是正确的方法吗?
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看起来很浪费。
当前回答
对于添加到数组中的新元素,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);
其他回答
正如@nilgun在评论中提到的,你可以使用react不可变helper。我发现这非常有用。
从文档中可以看出:
简单的推
var initialArray = [1, 2, 3];
var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]
initialArray仍然是[1,2,3]。
this.setState((prevState) => {
const newArray = [...prevState.array];
newArray[index] = updatedValue;
return { array: newArray };
});
我试图在数组状态下推值,并像这样设置值,并通过映射函数定义状态数组和推值。
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})
})
对于添加到数组中的新元素,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);
目前很多人都面临着更新useState钩子状态的问题。我使用这种方法来安全地更新它,并想在这里分享它。
这就是我的状态
const [state, setState] = useState([])
假设我有一个对象名为obj1,我想把它附加到我的状态中。我建议这样做
setState(prevState => [...prevState, obj1])
这将安全地在末尾插入对象,并保持状态一致性