我正在通过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;
答案 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>