こんにちはみんなreactjsの新人です私はajaxデータの結果が以前の状態と異なるときにコンポーネント(通知コンポーネント)をレンダリングできる反応方法、メソッド/ライフサイクルを知りたいだけですか?
var NewsList = React.createClass({
getInitialState: function() {
return ({
data: [],
showNotif: false,
showLoading: false
});
},
showNotification: function() {
return (
<Notification msg="new data" />
);
},
ajaxRequest: function() {
//do ajax request, load the result to this.state.data
},
componentWillMount: function() {
this.setState({showLoading: true});
},
componentDidMount: function() {
this.ajaxRequest();
setInterval(this.ajaxRequest, 2000);
},
componentDidUpdate: function(prevProps, prevState) {
if (this.state.data != prevState.data) {
//this.setState({showNotif: !this.state.showNotif});
}
},
render: function() {
var loadingElement, notifElement;
if (this.state.showLoading) {
loadingElement = <Loader />
}
if(this.state.showNotif) {
notifElement = this.showNotification();
}
return (
<div>
{notifElement}
{loadingElement}
<NewsItem data={this.state.data} />
</div>
);
});
したがってComponentDidUpdate
、変更されたstate.dataが読み取られ、変更された場合(ajaxの結果が新しく更新された場合)、がに設定さthis.state.showNotif
れtrue
てレンダリングが呼び出されますshowNotification()
が、そうではありません(点滅、true-falseセットバック、 4番目なので、何度も呼び出されます)
それを達成して正しくするために私は何をすべきですか?
これを行う最良の方法は、以前と異なる場合にのみデータ状態を更新することです。例えば:
componentDidMount(){
this.ajaxRequest().done((data)=>{
if(data !== this.state.data){
this.setState({data: data, showNotif: true})
})
ただし、毎回状態を更新して変更を確認する場合は、componentWillReceivePropsを使用することをお勧めします。
componentWillReceiveProps(nextProps, nextState) {
if (this.state.data != nextState.data) {
this.setState({showNotif: true});
}
}
違いは、データの状態を変更するとコンポーネントのレンダリングが発生し、その後componentDidUpdateでコンポーネントを2回目にレンダリングすることです(次のsetState)。componentWillReceivePropsを使用する場合-コンポーネントは1回だけレンダリングします。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加