1. 程式人生 > >React學習筆記之react進階篇(2)

React學習筆記之react進階篇(2)

-s state ops category strong tro 服務 ive 周期

2.組件與服務器通信

  組件的生命周期分為三個階段:掛載階段->更新階段->卸載階段,本文主要集中講述掛載和更新階段組件如何和服務器進行通信。

1.組件掛載階段通信

 1.componentDidMount()中進行通信

componentDidMount(){
    var that = this;
    fetch(‘/path/to/user-api‘).then(function(response){
        response.json().then(function(data){
            that.setState({user:data})
            });
        });
     }
}

 2.componentWillMount()中進行通信

componentWillMount(){
    var that = this;
    fetch(‘/path/to/user-api‘).then(function(response){
        response.json().then(function(data){
            that.setState({user:data})
            });
        });
     }
}

  

2.組件更新階段通信

 componentWillReceiveProps()中進行通信

componentWillReceiveProps(nextProps){
    if(nextProps.category!=this.props.category){                      //判斷原本的props是否發生變化,若沒有發生變化則不需要進行更新
        fetch(‘/path/to/user-api?category=‘+nextProps.category).
then(function(response){
            response.json().then(function(data){
                that.setState({users:data})
            });
           });
        }
    }
}

  

React學習筆記之react進階篇(2)