我正在尝试使用 setState 更改状态数组中对象键的值。更改的方式应该是仅更改索引 i
数组中对象的特定值。该索引的传递方式如下
import React from "react";
import {Button} from 'react-bootstrap';
class StepComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{
step: "Step1",
visited: false
},
{
step: "Step2",
visited: false
},
{
step: "Step3",
visited: false
}
]
};
}
nextStep(i) {
//Change the visited value of object from data[i] array from false to true
//Something like below
this.setState({
data[i]:visited to true
})
}
render(){
let visitSteps = this.state.data;
return(
<div>
{visitSteps.map((visitedStep, index) => (
<div key={index}>
<p>{visitedStep.step}</p>
<Button onClick={() => this.nextStep(i)}>Continue</Button>
</div>
))}
</div>
)
}
}
export default StepComponent
根据上面给出的每个 onClick
事件的示例,访问的特定对象值从 false
更改为 true
最佳答案
您可以使用等于您的数据的数组创建一个变量,更改作为输入传递的索引,然后调用传递新数组的设置状态。
nextStep(i) {
let visitesList = [...this.state.data];
visitesList[i].visited = true;
this.setState({
data: visitesList
})
}
如果您只想一次执行一个步骤,您可以使用 map 函数
nextStep(i) {
this.setState({
data: this.state.data.map((e, index) => {
e.visited = i === index;
return e;
})
});
}
此外,在 Button
上调用 nextStep
时,请使用 nextStep(index)
来调用
关于javascript - 如何使用特定数组索引更改状态数组的对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59283258/