对象无效作为React子对象(找到:具有键{}的对象)

时间:2017-08-15 19:36:42

标签: reactjs

我正在通过socket.io将对象发送到这样的react应用程序:

function getApiAndEmit(socket, quote) 
{
    try 
    {
        var { ticker, type, price, size, timestamp } = quote;
        socket.emit("FromAPI", quote);
        //console.log(ticker, type, price, size, timestamp)
    } 
    catch (error) 
    {
        console.error(`Error: ${error.code}`);
    }
};

当我尝试在客户端渲染它时,我收到错误:

If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.

使用react在网络浏览器上呈现字段的正确方法是什么?

代码

import React, { Component } from "react";
import socketIOClient from "socket.io-client";

class App extends Component {
  constructor() {
    super();
    this.state = {
      response: {},
      endpoint: "http://127.0.0.1:4001"
    };
  }

componentDidMount() {
    const { endpoint } = this.state;
    const socket = socketIOClient(endpoint);
    socket.on("FromAPI", data =>  this.setState({ response: data }));
  }

render() {
    const { response } = this.state;
    return (
      <div style={{ textAlign: "center" }}>
        {response
          ? <ul>
              Quote: {response}
            </ul>
          : <p>Loading...</p>}
      </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:11)

React无法渲染对象。要立即绕过错误,请输入以下内容:

{
    response
        ? <ul><li>Quote: {JSON.stringify(response)}</li></ul>
        : <p>Loading...</p>
}

如果response是一个字符串数组:

<ul>Quote: { response.map((item, index) => (<li key={index}>{item}</li>)) }</ul>

如果response是一个对象数组:

<ul>Quote: { response.map((item, index) => (<li key={index}>{item.quote}</li>)) }</ul>

如果response是对象:

<ul><li>Quote: {response.quote}</li></ul>