更新数据时的React.js生命周期

React.js cycle of life when updating data

本文关键字:js 生命 周期 React 数据 更新      更新时间:2023-09-26

我想要什么:

我有一个node.js服务器、一个captor和一个react.js客户端。每次捕获器检测到什么东西时,它都会通过socket.io向我的节点服务器发送一条消息,该消息会将数据返回到我的React网站(JSON)。

我希望每次我的客户端React.js从我的服务器接收到新数据时,它都会自动刷新指定的组件(通常是图表)。

我的代码:

Index.jsx

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {data: []};
    socket.on('dataCards', function (cards) {
      this.state = {data: cards};
    });
  }
  render () {
    return (
      <div className="container-fluid">
        <NavBarTop />
        <div className="row">
          <NavFilter />
          <div className="col-sm-7-5 col-md-7-5" id="mainPage">
            <DataAnalytics />
            <CardsList data={this.state.data} />
          </div>
          <Interventions />
        </div>
      </div>
    );
  }
}
render(<App />, document.getElementById('container'));

卡片列表.jsx:

import React from 'react';
class Card extends React.Component {
  constructor(props) {
    super(props);
  }
  rawMarkup() {
    var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
    return { __html: rawMarkup };
  }
  render() {
    return (
      <div className="ticket">
        <h2 className="cardUID">
          {this.props.uid}
        </h2>
        <span dangerouslySetInnerHTML={this.rawMarkup()} />
      </div>
    );
  }
}
export default Card;

我对React.js的生命周期不是很熟悉。不幸的是,在数据到达我的客户端之前调用了render。因此,当调用cardlist.jsx时,props.data为null。

我不知道如何构建我的代码来做我想做的事情。。。

有人能帮我吗?

第一次渲染时不会有数据。只是在这期间抛出一个装载指示器或其他什么东西。您应该在componentDidMount或componentWillMount中加载数据。

您需要使用setState函数来更新您的状态。它将触发您的组件的重新发布。只使用"this.state=something"来设置组件的初始状态。

socket.on('dataCards', (cards) => {
    this.setState({data: cards});
});

您可能希望使用componentWillMount或componentDidMount生命周期挂钩来侦听socket.io并停止侦听componentWillUnmount挂钩。

componentDidMount() {
    socket.on('dataCards', (cards) => {
        this.setState({data: cards});
    });
}
componentWillUnmount() {
    socket.off('dataCards');
}

此外,你的卡组件在我看来很奇怪。但我没有关于你的代码的详细信息来提供一些建议。