简体   繁体   English

ReactJS SocketIO setState到JSON对象

[英]ReactJS SocketIO setState to JSON Object

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 从我以前的线程这里有带有套接字嵌套JSON解析数据问题的ReactJS ,我试图找出最好的方法来设置我的react组件的setState并使状态为JSON

An example of my code would be here for the JSON: 我的代码示例将在此处显示JSON:

{
    "Object1": {
        "name": "1",
        "rank": "2"
    },
    "Object2": {
        "name": "3",
        "rank": "4"
    }
}

In my React code, I am setting state as such. 在我的React代码中,我正在这样设置状态。

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? 可以将setState作为JSON对象做什么,以便我可以随时在应用程序中使用数据?

Parse it before the setState and refer to the state directly: setState之前解析它,并直接引用状态:

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>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM