ahe*_*iot 126 javascript reactjs
我试图找到从组件状态中的数组中删除元素的最佳方法.既然我不应该this.state直接修改变量,那么从数组中删除元素是否有更好的方法(更简洁)?
onRemovePerson: function(index) {
this.setState(prevState => { // pass callback in setState to avoid race condition
let newData = prevState.data.slice() //copy array from prevState
newData.splice(index, 1) // remove element
return {data: newData} // update state
})
},
Run Code Online (Sandbox Code Playgroud)
谢谢.
更新
这已更新为使用setState中的回调.这应该在更新时引用当前状态时完成.
eph*_*ion 128
我见过的最干净的方法是filter:
removeItem(index) {
this.setState({
data: this.state.data.filter((_, i) => i !== index)
});
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*nan 87
你可以使用update()不变性帮助器react-addons-update,它可以在引擎盖下有效地做同样的事情,但是你正在做的事情很好.
this.setState(prevState => ({
data: update(prevState.data, {$splice: [[index, 1]]})
}))
Run Code Online (Sandbox Code Playgroud)
psc*_*scl 60
我相信this.state内部的引用setState()是不鼓励的
https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
文档建议使用setState()回调函数,以便在更新发生时在运行时传入prevState.所以这就是它的样子:
使用没有ES6的Array.prototype.filter
removeItem : function(index) {
this.setState(function(prevState){
return { data : prevState.data.filter(function(val, i) {
return i !== index;
})};
});
}
Run Code Online (Sandbox Code Playgroud)
将Array.prototype.filter与ES6箭头函数一起使用
removeItem(index) {
this.setState((prevState) => ({
data: prevState.data.filter((_, i) => i !== index)
}));
}
Run Code Online (Sandbox Code Playgroud)
使用immutability-helper
import update from 'immutability-helper'
...
removeItem(index) {
this.setState((prevState) => ({
data: update(prevState.data, {$splice: [[index, 1]]})
}))
}
Run Code Online (Sandbox Code Playgroud)
使用Spread
function removeItem(index) {
this.setState((prevState) => ({
data: [...prevState.data.slice(0,index), ...prevState.data.slice(index+1)]
}))
}
Run Code Online (Sandbox Code Playgroud)
请注意,在每个实例中,无论使用何种技术,this.setState()都会传递一个回调,而不是旧的对象引用this.state;
evi*_*ing 23
这是一种使用ES6扩展语法从状态中的数组中删除元素的方法.
onRemovePerson: (index) => {
const data = this.state.data;
this.setState({
data: [...data.slice(0,index), ...data.slice(index+1)]
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88854 次 |
| 最近记录: |