2016-09-21 7 views
0

私はreactjsで新しい人です ajaxデータの結果が前の状態と異なる場合、コンポーネント(通知コンポーネント)をレンダリングできる反応方法、メソッド/ライフサイクルを知りたいだけですか?reactjs:データが変更されたことを検出して通知を表示する方法

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結果を意味する)変わったのならば、それはtruethis.state.showNotifを設定し、showNotification()を呼び出しますレンダリングします見ることができますが、それはだ場合(点滅している、真偽が前後に設定されているので何度も呼び出される)

これを達成して正しくするためにはどうすればよいですか?

+1

もしあなたが 'if(isDifferent(this.state.data、ajaxData)){this.state.data、{data:ajaxData、showNotif:trueのように状態を保存する前に新しいデータが* })} ' – ezakto

+0

素晴らしい、私はあなたのポイントを見ることができ、何とかそれは働いています。これは良い練習かどうか分かりませんが、ありがとうございます。 –

+0

'this.state.data!= prevState.data'はいつも' true'を与えます。あなたはlodashから '_.isEqual()'のようなものが必要です –

答えて

0

これを行う最良の方法は、前と異なる場合にのみデータ状態を更新することです。

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 - componentレンダリングを使用するのは1回だけです。

関連する問題