ReactJS with Sockets Nested JSON parsing data issue

青春壹個敷衍的年華 提交于 2019-12-02 09:08:21

问题


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

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

and in my React code, I have my data to set my react state. I want to pass Object2 to a different component, but I can't seem to differentiate the data.

// import packages
import React, { Component } from "react";
import io from 'socket.io-client';

class App extends Component {
    constructor() {
        super();

        this.state = {
            data: null
        };
        this.socket = io('http://localhost:5000');

        // Binders
        this.updateState = this.updateState.bind(this);
    }

    componentDidMount() {
        this.socket.on('send data', this.updateState);
    }

    updateState(result) {
        this.setState({
            data: result
        });
    }

    render() {
        return (
            <p style={{ textAlign: "center" }}>
                {this.state.data}
            </p>
        );
    }
}

export default App;

When I try to reference something like this.state.data or this.state.data.Object1.name, it points to a null object. What am I doing wrong?


回答1:


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 <div>
      {!this.state.data ? "No data yet, wait 2 seconds." : this.state.data.Object1.name }
    </div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

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



来源:https://stackoverflow.com/questions/51868837/reactjs-with-sockets-nested-json-parsing-data-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!