我需要从 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);
关于javascript - React 在 componentDidMount() 的函数内设置状态,传递要更新的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55229011/