![](/img/trans.png)
[英]React.js component life cycle, state behavior and asynchronous nature of JavaScript
[英]React.js cycle of life when updating data
我想要的是 :
我有一个node.js服务器,一个捕获器和一个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'));
cardlist.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');
}
您的Card组件对我来说也很奇怪。 但是我没有有关您的代码的详细信息以提供建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.