admin 管理员组文章数量: 1086019
I asked myself if there is a clean, proper way to swap two objects in an array using setState
. This is what I currently do:
export function moveStepUp(index) {
if(index > 0){
let currentStep = this.state.stepsData[index];
let stepAbove = this.state.stepsData[index - 1];
this.setState((prevState) => ({
stepsData: prevState.stepsData.map((step, i) => {
if(i === index - 1)
return {
...currentStep,
position: i
};
if(i === index)
return {
...stepAbove,
position: i
};
return step;
})
}), () => console.log(this.state.stepsData));
}
}
This code is working, but I thought there might be a better solution. It seems like too much lines of code for such a simple task. Thanks!
I asked myself if there is a clean, proper way to swap two objects in an array using setState
. This is what I currently do:
export function moveStepUp(index) {
if(index > 0){
let currentStep = this.state.stepsData[index];
let stepAbove = this.state.stepsData[index - 1];
this.setState((prevState) => ({
stepsData: prevState.stepsData.map((step, i) => {
if(i === index - 1)
return {
...currentStep,
position: i
};
if(i === index)
return {
...stepAbove,
position: i
};
return step;
})
}), () => console.log(this.state.stepsData));
}
}
This code is working, but I thought there might be a better solution. It seems like too much lines of code for such a simple task. Thanks!
Share Improve this question edited Feb 16, 2018 at 9:32 Mayank Shukla 105k19 gold badges162 silver badges145 bronze badges asked Aug 31, 2017 at 7:18 NoceboNocebo 2,0373 gold badges18 silver badges28 bronze badges2 Answers
Reset to default 7Why not simply swapping two array values by using a third variable if you know the element index.
First copy the array in another variable, swap two array values, then use setState
to update the state value.
Like this:
this.setState(prevState => {
let data = [...prevState.data];
let temp = data[index-1];
data[index-1] = data[index];
data[index] = temp;
return { data };
})
Instead of spread operator, you can use any other way to create a copy of array.
In react hooks you can use this, this works for me
const [array,setArray]= useState([]);
setArray(array => {
let data = [...array];
let temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
console.log(data);
return data ;
})
本文标签: javascriptSwapping two objects in array ReactJSStack Overflow
版权声明:本文标题:javascript - Swapping two objects in array: ReactJS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744036912a2522535.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论