如何使用setState插入React的状态数组? [英] How can I insert into React's state array with setState?
本文介绍了如何使用setState插入React的状态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在react中进行修改和排列,并在特定索引上插入元素.这是我的状态:
I'm looking to modify and array in react and insert elements on specific index. This is how my state looks like:
this.state = {arr: ['', '', '', '' ]}
我想做的是编译此arr[index] = 'random element'
以响应js setState语法.我想做的是:
What I wanna do is to compile this arr[index] = 'random element'
to react js setState syntax. What I tried to do was:
this.setState({ arr[index]: 'random element' })
但是失败了,ty!
推荐答案
使用slice()
克隆当前状态.这样,原始状态将保持不受影响,直到setState()
.克隆后,对克隆的阵列进行操作并将其设置为状态.先前的答案将变异状态.在此处阅读有关内容
Clone the current state using slice()
. By doing this, the original state remains unaffected till setState()
. After cloning, do your operations over the cloned array and set it in the state. The previous answer will mutate the state. Read about this here
let a = this.state.arr.slice(); //creates the clone of the state
a[index] = "random element";
this.setState({arr: a});
这篇关于如何使用setState插入React的状态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文