react组件与服务器通信

component的生命周期图

需要关注的是在render执行前后执行的componentWillMount(),componentDidMount();  属性props改变执行的componentWillReceivePros(nextPros); state或props改变会执行的 shouldComponentUpdate(nextProps , nextState), componentWillUpdate(nextProps,nextState), componentDidUpdate(nextProps,nextState);

组件挂载阶段的通信:

由于与服务器交互很大可能会改变state props 或其他普通属性值。所以一般在页面被渲染完成之后确保dom元素都存在的情况下在与后台做数据交互。因此,采用componentDidMount()方法进行通信较为稳妥。

组件更新阶段的通信:

该阶段props或state会有改变,这时向后台请求数据。可供选择的方法有shouldComponentUpdate(nextProps,nextState),componentWillUpdate(nextProps,nextState), componentDidUpdate(nextProps,nextState); 若是props改变还可以选择componentWillReceivePros(nextPros);

其中:

1.shouldComponentUpdate(nextProps,nextState)该方法一用于判断props 和 state是否有改变。且防止stat快速变化的问

   题。返回值为true或false,不适用于与后台数据交互。原始的state和props 可以用 this.props this.state表示。

2.componentWillUpdate(nextProps,nextState):该方法执行后会立马把nextProps 和 nextState覆盖原来的props和state,因此不

   适用于调用setState()方法,在某些情况下也不适用于数据交互。

3.componentWillReceivePros(nextPros); 这里是安全的,可以用于交互(正确答案

4.componentDidUpdate(nextProps,nextState);一般用于组件渲染结束之后调用,已经渲染结束了,在改变state会造成再一次的渲染,不适用于数据交互。

扩展:setState(preState),可以调用原始state

猜你喜欢

转载自blog.csdn.net/u011862930/article/details/88066493