组件与服务器通信
组件从服务器上获取数据,不包含组件向服务器提交数据的情况。
组件挂载阶段通信
React 组件的正常运转本质上是组件不同生命周期方法的有序执行,因此组件与服务器的通信也必定依赖组件的声明周期方法。
jsx
export default class UserListContainer extends Component {
// 省略无关代码
render() {
return (
<div>
<h1>UserListContainer</h1>
</div>
);
}
componentDidMount() {
fetch('/path/api').then(res => {
res.json().then(data => {
this.setState({
users: data,
});
});
});
}
}componentDidMount 是官方推荐的通信周期,当然 componentWillMount 也是可以的。
componentDidMount 中执行服务器通信可以保证获取数据时,组件已经处于挂载状态,即便操作 DOM 也是安全的,而 componentWillMount 无法保证
当组件在服务端渲染时,componentWillMount 会被调用两次,一次是服务端,一次是浏览器端,而 componentDidMount 能保证在任何情况下只调用一次,从而不会发送多余的请求
组件更新阶段通信
componentWillReceiveProps 非常适合做更新阶段的服务器通信。
jsx
class UserListContainer extends Component {
// 省略
componentWillReceiveProps(nextProps) {
if (nextProps.category !== this.props.category) {
fetch(`/path/api?category=${nextProps.category}`).then(res => {
res.json().then(data => {
this.setState({
users: data,
});
});
});
}
}
}这里需注意:在执行 fetch 请求时,要先对新老 props 中的 category 作比较,有不一致才进行更新。componentWillReceiveProps 并不能保证 props 一定发生了修改
