首页 > 解决方案 > 无法将来自套接字 io 的数据作为道具传递给反应组件

问题描述

我尝试了几种方法,但似乎没有任何效果:(我试图通过构建一个实现 Socket io 的简单应用程序来学习 React,但找不到将“响应”作为道具传递给子组件的方法。

import socketIOClient from "socket.io-client";
import Main from "./Main";
const ENDPOINT = "http://127.0.0.1:4001";


function App() {
  const [response, setResponse] = useState([]);


  useEffect(() => {
    const socket = socketIOClient(ENDPOINT);
    socket.on("tick", (data) => {
      setResponse(data);
    });
  }, []);

  console.log(response);
 
  return (
    <>
      <div style={{ textAlign: "center" }}>
        <Main
         responses = {response}
        />
      </div>
    </>
  );
}

export default App;
import React from 'react';
import './Main.css';

class Main extends React.Component {

  render() {



   return (
      <div className="container">
        <div className="placeholder">hello {this.props.responses}</div>
        <div className="placeholder"></div>
        <div className="placeholder"></div>
      </div>
    );
  }
}

export default Main;

我收到这个错误

× × 错误:对象作为 React 子对象无效(找到:对象与键 {currencyPairName, prices})。如果您打算渲染一组子项,请改用数组。▶ 22 个堆栈帧被折叠。插座。src/App.js:14

11 | useEffect(() => {
  12 |   const socket = socketIOClient(ENDPOINT);
  13 |   socket.on("tick", (data) => {
> 14 |     setResponse(data);
     | ^  15 |   });
  16 | }, []);
  17 | 

我的响应包含一个对象数组

希望有人能告诉我光..

标签: javascriptarraysreactjssocket.iocomponents

解决方案


推荐阅读