简体   繁体   English

React.JS 将 websocket 值更新为对象

[英]React.JS update a websocket value into an object

I am tring to dynamically create a stock price table with live stock price using websockets.我正在尝试使用 websockets 动态创建一个带有实时股票价格的股票价格表。 I am getting all the nexessary data and want to update my object value for stock price with the live price.我正在获取所有必要的数据,并希望用实时价格更新股票价格的对象值。 How do I access the variable and insert value into the object.如何访问变量并将值插入到对象中。 The data variable gets the live stock price.数据变量获取实时股票价格。

import './App.css';
    import * as ReactBootStrap from "react-bootstrap";
    import { w3cwebsocket as W3CWebSocket } from "websocket";
    import React, { useEffect, useState } from 'react';



    function App() {
      
      const stockPrice = document.getElementById('stockPrice');  
      const [stocks, setStocks] = useState([0])
      const client = new W3CWebSocket('ws://localhost:9080/user');
    
      
      useEffect(() => {
        client.onopen = () => {
          console.log('connected to localhost:9080');
        }
        client.onmessage = (e) => {
          let page = JSON.parse(e.data);
          let x = page.Update;
          let data = x.Data[0].RowData[4];
          console.log(data);    
          function getData() {
            setStocks(currStock => currStock+data) ; 
          }            
        }
        return () => {         
        }
      }, [])
     
    
      const stocks1 = [
        {serialnumber:"1", accountnumber:"Account1", ticker: "AAPL", stockprice:""},
        {serialnumber:"2", accountnumber:"Account2", ticker: "GME", stockprice:""} ,
        {serialnumber:"3", accountnumber:"Account3", ticker: "IBM", stockprice:""} ,
        {serialnumber:"4", accountnumber:"Account4", ticker: "CS", stockprice:""} ,
        {serialnumber:"5", accountnumber:"Account5", ticker: "MSFT", stockprice:""} ,
        {serialnumber:"6", accountnumber:"Account6", ticker: "INTC", stockprice:""}   ]
       
      
        const renderStocks = (stock, index) => {
          return(
            <tr key={index}>
              <td>{stock.serialnumber}</td>
          <td>{stock.accountnumber}</td>
          <td>{stock.ticker}</td>
          <td id="stockPrice">{stock.stockprice}</td>
            </tr>
      
          )
         
        }    
     
    
      return (
        <div className="App">
          <ReactBootStrap.Table striped bordered hover>
        <thead>
          <tr>
            <th>Serial Number</th>
            <th>Account Number</th>
            <th>Ticker</th>
            <th>Stock Price</th>
          </tr>
        </thead>
        <tbody>
          {stocks1.map(renderStocks)}
        </tbody>
        </ReactBootStrap.Table>
        </div>
      );
    }
    
    export default App;

There are two things you should implement.您应该实施两件事。 The first one is to keep your actual data as state.第一个是将您的实际数据保留为状态。 For functional components you can do it using 'useState' hook.对于功能组件,您可以使用“useState”钩子来完成。 The second one is keeping fetching within 'useEffect' hook.第二个是在“useEffect”钩子中保持获取。 Finally you should come to something like this:最后你应该得到这样的结果:

const App = () => {
  const [stocks, setStocks] = useState([])
  useEffect(() => {
    // here you open websocket connection just like you do it now
    ...
    client.onmessage = () => {
      // here you get the updated details
      setStocks({objectWithNewStocksDetails}) // react, update state please
    }
    
    return () => {} // useEffect returns cleanup function - close connection here

  }, []) // an empty dependencies array says it fires once

  // after all you just return jsx
  // btw you can use conditional returns in case you do not have data to show yet:
  if (stocks.length === 0) return <div>Loading...</div>

  return (
    <div className="App">
      ...
    </div>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM