[英]React setting state inside function on componentDidMount() passing parameters to be updated
我需要从componentDidMount()中的函数更新组件状态对象元素。 理想情况下,我希望能够传递我需要更新的元素以及我想用来更新它的值。 我确实知道“ this”是未定义的,并且我已经看到了带有箭头功能的解决方案,但是我似乎无法使其正常工作。
从componentDidMount()内部的函数传递要更新的元素和值的状态来更新状态的最佳方法是什么?
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;
尝试这个
websocket.onmessage = (function (event) {
//this.updateState(itemone "off");
this.setState({
obj: {
itemone: "off"
}
});
}).bind(this);
鉴于你无法使用箭头功能,可以规避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}
})
}
}
您可以尝试arrow function
websocket.onmessage = (event) => {
//this.updateState(itemone "off");
this.setState({ //undefined
obj: {
itemone: "off"
}
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.