ReactJS with Sockets Nested JSON 解析数据问题

ReactJS with Sockets Nested JSON parsing data issue

我有一个 JSON 文件,其结构如下 "data.json"

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

在我的 React 代码中,我有我的数据来设置我的反应状态。我想将 Object2 传递给不同的组件,但我似乎无法区分数据。

// 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;

当我尝试引用 this.state.data 或 this.state.data.Object1.name 之类的内容时,它指向一个空对象。我究竟做错了什么?

我不太了解套接字,但由于您是在第一次渲染后设置状态,因此在 componentDidMount 完成其工作之前没有任何数据。所以,你需要条件渲染。

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>

你不能使用 {this.state.data} 因为 React 子对象不能是对象。您需要使用此对象的值。