From my previous thread here ReactJS with Sockets Nested JSON parsing data issue , I am trying to figure out the best way to setState of my react component and have the state be of JSON
An example of my code would be here for the JSON:
{
"Object1": {
"name": "1",
"rank": "2"
},
"Object2": {
"name": "3",
"rank": "4"
}
}
In my React code, I am setting state as such.
componentDidMount() {
this.socket.on('send data', this.updateState);
}
updateState(result) {
this.setState({
data: result
});
this.toObj = JSON.parse(this.state.data);
}
What can I do to setState as a JSON object so I can readily use the data in my app?
Parse it before the setState
and refer to the state directly:
updateState(result) {
const data = JSON.parse(result);
this.setState({
data
});
}
render() {
return (
<ul>
{this.state.data.map(obj => (
<li><span>{obj.name}</span>: <span>{obj.rank}</span></li>
)}
</ul>
)
}
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.