带套接字嵌套JSON解析数据的ReactJS问题 [英] ReactJS with Sockets Nested JSON parsing data issue

查看:70
本文介绍了带套接字嵌套JSON解析数据的ReactJS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON文件,其结构类似于"data.json"

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

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

,在我的React代码中,我有数据来设置我的React状态.我想将Object2传递给其他组件,但是我似乎无法区分数据.

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;

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

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?

推荐答案

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

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>

您不能使用{this.state.data},因为React子对象不能成为对象.您需要使用该对象的值.

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

这篇关于带套接字嵌套JSON解析数据的ReactJS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆