如何在 React 中更新 render() 中的值?

How to update the value in render() in React?

我想显示从 websocket 获取的数据。当 render 函数不存在时被调用。当 websocket 发送数据但它不工作时,我尝试用 this.state 更新它。我正在使用 recharts 来显示条形图,在数据中我需要来自 WebSocket 的值。

index.js

import _ from 'lodash';
import style from './style.css';
import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom';
import {
  BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, LabelList, Label
} from 'recharts';

var data;

class Example extends React.Component {

    constructor(props) {
  super(props);
  //setting a default value
  this.state = { data: [{time:23.30,value:288.65},{Energy:0,value:0.0}] };
}

//componentDidMount() {
    //this.state = { data: data };
    //console.log("compMount");
//}

  render() {
      //verbinde();
      var connection = new WebSocket('ws://next-gen-rz.hs-harz.de:8080/fhem_prototyp2/Test');
        connection.onopen = function () {
            connection.send('day');
            console.log("gesendet: day");
        };
            // Log errors
        connection.onerror = function (error) {
            console.log('WebSocket Error ' + error);
        };

        // Log messages from the server
        connection.onmessage = function (e) {
            console.log('Server: ' + e.data);
            this.setState = {data: e.data };
        };


    return (

      <BarChart
        width={800}
        height={500}
        data={this.state.data}
        margin={{
          top: 5, right: 30, left: 20, bottom: 5,
        }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="time" tick={{ fill: 'white'}}/>
        <YAxis tick={{ fill: 'white' }} label={{ value: 'kWh', angle: -90, position: 'insideLeft' }}>
        </YAxis>
        <Bar name="Wochenverbrauch" dataKey="value" fill="#f59f4a" >
        <LabelList dataKey="value" position="top" fill='white'/>
        </Bar>
      </BarChart>
    );
  }

}
ReactDOM.render(<Example />, document.getElementById("left"));

你不能通过改变状态来更新,你需要调用函数:

this.setState(newState)

并提供 newState 对象。参见 https://reactjs.org/docs/react-component.html#setstate

另外,你不能在render函数中设置状态,你需要在componentDidMount中获取数据,然后在那里设置状态。

您应该在 componentDidMount 方法生命周期中只打开一次 websocket 连接。

要更新状态,您应该调用 setState 函数

您还需要在componentWillUnmount方法中关闭websocket连接以避免内存泄漏

class Example extends React.Component {

 constructor(props) {
   super(props);
   //setting a default value
   this.state = { data: [{time:23.30,value:288.65},{Energy:0,value:0.0}] };
 }

 componentDidMount() {
    const that = this;

    that.connection = new WebSocket(
      'ws://next-gen-rz.hs-harz.de:8080/fhem_prototyp2/Test'
    );

    that.connection.onopen = function () {
        that.connection.send('day');
    };
        // Log errors
    that.connection.onerror = function (error) {
        console.log('WebSocket Error ' + error);
    };

    // Log messages from the server
    that.connection.onmessage = function(e) {
        console.log('Server: ' + e.data);
        that.setState({data: e.data });
    };
 }

 componentWillUnmount() {
    this.connection && this.connection.close();
 }

 render() {
   return (
     <BarChart
       width={800}
       height={500}
       data={this.state.data}
       margin={{top: 5, right: 30, left: 20, bottom: 5}}
     >
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="time" tick={{ fill: 'white'}}/>
      <YAxis 
          tick={{ fill: 'white' }} 
          label={{ value: 'kWh', angle: -90, position: 'insideLeft' }}
      />
      <Bar name="Wochenverbrauch" dataKey="value" fill="#f59f4a" >
        <LabelList dataKey="value" position="top" fill='white'/>
      </Bar>
    </BarChart>
  );
 }
}