Javascript 在传递要更新的参数的componentDidMount()上,在函数内部反应设置状态
我需要从componentDidMount()内的函数更新组件状态对象元素。理想情况下,我希望能够传递我需要更新的元素和我想要更新的值。我确实理解“this”是未定义的,并且我已经看到了使用箭头函数的解决方案,但我似乎无法让它工作 从传递要更新的元素和值的componentDidMount()内的函数更新状态的最佳方法是什么Javascript 在传递要更新的参数的componentDidMount()上,在函数内部反应设置状态,javascript,reactjs,Javascript,Reactjs,我需要从componentDidMount()内的函数更新组件状态对象元素。理想情况下,我希望能够传递我需要更新的元素和我想要更新的值。我确实理解“this”是未定义的,并且我已经看到了使用箭头函数的解决方案,但我似乎无法让它工作 从传递要更新的元素和值的componentDidMount()内的函数更新状态的最佳方法是什么 class App extends Component { constructor(props) { super(props); this.state
class App extends Component {
constructor(props) {
super(props);
this.state = {
obj: {
itemone: "on",
itemtwo: "off"
}
};
}
// updateState(item, valStr) {
// this.setState({
// obj: {
// item: valStr
// }
// });
// };
componentDidMount() {
//.......
websocket.onmessage = function (event) {
//this.updateState(itemone "off");
this.setState({ //undefined
obj: {
itemone: "off"
}
});
};
}
render() {
return (
<div className="App">
...
</div>
);
}
}
export default App;
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
obj:{
第一条:“开”,
第二项:“关闭”
}
};
}
//更新不动产(项目,VALTR){
//这是我的国家({
//obj:{
//项目:VALTR
// }
// });
// };
componentDidMount(){
//.......
websocket.onmessage=函数(事件){
//本不动产(第1项“关闭”);
此.setState({//未定义
obj:{
项目一:“关闭”
}
});
};
}
render(){
返回(
...
);
}
}
导出默认应用程序;
试试这个
websocket.onmessage = (function (event) {
//this.updateState(itemone "off");
this.setState({
obj: {
itemone: "off"
}
});
}).bind(this);
鉴于您无法使用箭头函数,您可以通过以下方式规避未定义的
此
:
componentDidMount() {
// Define a variable pointing to the `this` of the class
const newThis = this
websocket.onmessage = function (event) {
// Use that this to call the setState
newThis.setState(prevState => {
const newObj = prevState.obj
newObj.itemone = "off"
return { obj: newObj}
})
}
}
您可以尝试
箭头功能
websocket.onmessage = (event) => {
//this.updateState(itemone "off");
this.setState({ //undefined
obj: {
itemone: "off"
}
});
};
这不是一个有键值对的对象,而不是一个元素数组吗?是的,这就是我的意思,我把我的答案写成了一个可行的解决方案。使用扩展操作符来设置状态,比如-
this.setState({…this.state,obj:{…this.state.obj,itemone:“off”})代码>