![](/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.