I need to update component state object elements from function inside componentDidMount(). Ideally I want to be able to pass the element I need to update and the value I want to update it with. I do understand "this" is undefined and I have seen solutions with arrow functions but I can't seem to get it to work.
What would be the best approach to update state from function inside componentDidMount() passing element and value to be updated?
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;
try this
websocket.onmessage = (function (event) {
//this.updateState(itemone "off");
this.setState({
obj: {
itemone: "off"
}
});
}).bind(this);
Given your inability to use arrow functions, you can circumvent the this
coming undefined by:
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}
})
}
}
You can try the arrow function
websocket.onmessage = (event) => {
//this.updateState(itemone "off");
this.setState({ //undefined
obj: {
itemone: "off"
}
});
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.