我必须使用键style
找到所有状态值,并在下面的嵌套状态下使用red
更改值。
this.state = {
front: {
line1: {
style: "blue",
name: "name1"
},
line2: {
style: "blue",
name: "name2"
}
}
}
我已经做了类似的尝试,但它给出了错误。
Object.keys(this.state).forEach(function(k,prevState) {
this.setState(prevState => ({ [k]:
{...prevState[k], style: "red"}
}))
});
我该如何更新?
您可以在Object.keys
对象上使用front
来获取包含所有键名的数组,然后在其上使用reduce
并构建一个新的front
对象,您可以将所有style
属性更改为"red"
。
class App extends React.Component {
state = {
front: {
line1: {
style: "blue",
name: "name1"
},
line2: {
style: "blue",
name: "name2"
}
}
};
onClick = () => {
this.setState(({ front }) => ({
front: Object.keys(front).reduce((acc, key) => {
acc[key] = {
...front[key],
style: "red"
};
return acc;
}, {})
}));
};
render() {
return (
<div>
<button onClick={this.onClick}>Change to red</button>
<div>{JSON.stringify(this.state)}</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
你有问题,因为你没有使用箭头功能。你应该使用数组函数来访问qazxsw poi
setState
只需制作一个状态的副本,然后循环遍历它,并更改样式键的值并更新状态
Object.keys(this.state).forEach((k,prevState) => {
this.setState(prevState => ({ [k]:
{...prevState[k], style: "red"}
}))
});
我建议制作一种在州内设置红色样式的方法。您可以复制并粘贴下面的代码并根据自己的喜好进行编辑。
let copy = JSON.parse(JSON.stringify(this.state))
Object.keys(copy).forEach(e=>{
copy[key].style = 'red'
})
this.setState(copy)
您应该能够在onClick函数中调用setRedStyles()直接调用此函数。
您的问题发生是因为您在forEach回调中使用了ES5函数,这意味着回调函数具有函数作用域,其中setRedStyles = () => {
const newState = { ...this.state };
Object.keys(newState.front).forEach(prop => {
if (newState.front[prop].style) {
newState.front[prop].style = "red";
}
this.setState(newState);
});
}
指的是回调函数的上下文。
解决方案1:使用ES6箭头功能。箭头函数具有定义的范围。
this
解决方案2:使用Object.keys(this.state).forEach((k) => {
this.setState({ [k]: {...this.state[k], style: 'red' }})
});
方法。
bind()方法创建一个新函数,在调用时,将其this关键字设置为提供的值。
bind