有了这个code ,我能够在一个简单的对象上成功使用 setState
– 当我点击“Joey”时,名称会更改为“Igor”。
class Card extends React.Component {
myFunc = () => {this.props.change('Igor')};
render() {
return (
<p onClick={this.myFunc}>{this.props.name}</p>
)
}
}
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = { name: "Joey" }
}
toggle = (newname) => {
this.setState((prevState, props) => ({
name: newname
}));
}
render() {
return (
<Card change={this.toggle} name={this.state.name} />
);
}
}
但是有了这个code ,其中有多个嵌套在数组中的对象,setState
要么无法将每个名称更改为“Igor”,要么必须以某种方式进行修改。
class Card extends React.Component {
myFunc = () => {this.props.change('Igor')};
render() {
return (
<p onClick={this.myFunc}>{this.props.name}</p>
)
}
}
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
names: [
{
name: "Joey"
},
{
name: "Sally"
},
{
name: "Billy"
},
]
}
}
toggle = (newname) => {
this.setState((prevState, props) => ({
// what can I put here to change the name I click on to "Igor"
}));
}
render() {
const names = this.state.names.map((name, index) => (
<Card key={index} change={this.toggle} {...name} />
))
return (
<div>
{names}
</div>
);
}
}
即使我知道这不是 setState
的工作方式,我还是尝试通过传递 index
然后编写 this 来访问
.不足为奇,它没有用。name
.state.names[index].name: newname
虽然我发现很多关于不变性助手的提及,但我已经研究过但找不到关于 SO 的类似问题。但我仍然不确定这是否是要走的路。
使用 setState
修改嵌套在数组中的对象的最佳方法是什么?
最佳答案
已修改您的代码,可以找到工作示例here .
更改可以在这里找到:
toggle = (index, newname) => {
this.setState((prevState, props) => ({
// Return new array, do not mutate previous state.
names: [
...prevState.names.slice(0, index),
{ name: newname },
...prevState.names.slice(index + 1),
],
}));
}
render() {
const names = this.state.names.map((name, index) => (
// Need to bind the index so callback knows which item needs to be changed.
<Card key={index} change={this.toggle.bind(this, index)} {...name} />
))
return (
<div>
{names}
</div>
);
}
想法是,需要通过.bind
将索引传递给回调函数,并返回一个新的state
数组,修改后的名称。您需要传递索引,以便组件知道将哪个对象的 name
更改为 newname
。
关于javascript - 在 React JS 中,如何将 `setState` 与嵌套在数组中的对象一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43815959/