gpt4 book ai didi

javascript - React 在 componentDidMount() 的函数内设置状态,传递要更新的参数

转载 作者:行者123 更新时间:2023-12-02 23:59:42 24 4
gpt4 key购买 nike

我需要从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com