我希望在特定索引上修改和排列 react 并插入元素。这是我的状态:
this.state = {arr: ['', '', '', '' ]}
我想做的是编译这个 arr[index] = 'random element'
来响应 js setState 语法。我试图做的是:
this.setState({ arr[index]: 'random element' })
但是失败了,你!
最佳答案
使用 slice()
克隆当前状态。通过这样做,原始状态在 setState()
之前保持不受影响。克隆后,对克隆的数组进行操作并将其设置为状态。先前的答案将改变状态。阅读有关此内容的信息 here
let a = this.state.arr.slice(); //creates the clone of the state
a[index] = "random element";
this.setState({arr: a});
关于javascript - 如何使用 setState 插入 React 的状态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39941734/