如何使用 React js 更新特定索引处的数组 [英] How to update an array at a particular index with React js
本文介绍了如何使用 React js 更新特定索引处的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的构造函数中有一个状态数组:
I have a state array in my constructor:
constructor(props) {
super(props);
this.state = {myarray: []};
}
现在我想以特定的下标更新数组.
Now I want to update the array at a specific subscript.
this.setState({myarray[i]: 'test'});
给我一个 unexpected token
错误,指向左括号 [
gives me an unexpected token
error, pointing at the opening bracket [
这样做的正确方法是什么?
What is the correct way of doing that?
附言使用 push
方法动态填充数组,然后我才尝试更新
P.S. Array gets filled dynamically using push
method and only then I attempt to update
推荐答案
创建数组的副本:
const newArray = Array.from(this.state.myarray);
更新索引:
newArray[i] = 'test';
并更新状态
this.setState({myarray: newArray});
<小时>
您还可以使用 不可变的助手 (曾经是 React 插件的一部分) 以更简洁地做到这一点.
You can also use immutable helpers (used to be part of React's addons) to do this more concisely.
这篇关于如何使用 React js 更新特定索引处的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文