ReactJS with Sockets Nested JSON parsing data issue

前端 未结 1 1476
情歌与酒
情歌与酒 2021-01-23 16:22

I have a JSON file that has a structure like this \"data.json\"

{
    \"Object1\": {
        \"name\": \"1\",
        \"rank\": \"2\"
    },
    \"Object2\": {
          


        
1条回答
  •  清歌不尽
    2021-01-23 17:06

    I don't know so much about sockets but since you are setting the state after the first render, there isn't any data until componentDidMount finishes its job. So, you need conditional rendering.

    const data = {
      "Object1": {
        "name": "1",
          "rank": "2"
      },
      "Object2": {
        "name": "3",
          "rank": "4"
      }
    };
    
    const fakeRequest = () => new Promise( resolve => 
      setTimeout( () => resolve(data), 2000 )
    );
    
    class App extends React.Component {
      state = {
        data: null,
      };
    
      componentDidMount() {
        fakeRequest().then( data => this.setState({data}));
      }
    
      render() {
        return 
    {!this.state.data ? "No data yet, wait 2 seconds." : this.state.data.Object1.name }
    ; } } ReactDOM.render(, document.getElementById("root"));
    
    
    

    You can't use {this.state.data} since a React child can't be object. You need to use the values of this object.

    0 讨论(0)
提交回复
热议问题