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

时间:2019-05-17 22:48:57

标签: javascript reactjs recharts

我想显示从网络套接字获取的数据。当尚不存在时,将调用render函数。我尝试在websocket发送数据但无法正常工作时使用this.state更新它。我正在使用图表显示BarChart,在数据中,我需要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"));

2 个答案:

答案 0 :(得分:1)

您只能在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>
  );
 }
}

答案 1 :(得分:0)

您无法通过更改状态来进行更新,需要调用该函数:

this.setState(newState)

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

此外,您无法在render函数中设置状态,例如,您需要在componentDidMount中获取数据,然后在此处设置状态。