一、整体流程
1、装载——》2、更新——》3、卸载
二、具体流程
1.装载
componentDidMount()
在组件装载(mounting)(插入树)后被立即调用。初始化所需要的 DOM 节点的应该放在这里。 如果你需要从远程加载数据,这是一个实例化网络请求的好地方。
这种方法是设置任何 订阅(subscriptions) 的好地方。如果你这样做,不要忘了在 componentWillUnmount()
中 取消订阅(unsubscribe) 。
你可以立刻在 componentDidMount()
中调用setState()
。 它会触发额外的渲染, 但会在浏览器更新屏幕之前发生。在这种情况下,即使 render()
会被调用两次, 也可以保证用户不会看到中间状态。 请谨慎使用此模式,因为这通常会导致性能问题。 在大多数情况下,您应该能够在 constructor()
中分配初始 state(状态) 。但是,当你需要测量一个 DOM 节点,并在渲染一些依赖于它的大小或位置的东西之前,这种情况下,这种模式可能会非常有用。
componentDidMount() {
console.log("componentDidMount");
let query = {bg:this.props.params.bg};
this.props.dispatch(searchAuthorities(query))
}
2.更新
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
componentDidUpdate()
在更新发生后立即被调用。 这个方法在第一次渲染时不会被调用。
当组件已更新时,使用此方法作为操作 DOM 的一个机会。 这也是做网络请求的一个好地方,只需你比较当前 props 与以前的 props(例如,如果 props 没有改变,可能不需要网络请求)。
你可以在 componentDidUpdate()
中 立即调用 setState()
,但请注意,必须包含在条件语句中 像上面的例子一样,否则你会导致无限循环。 这也会导致额外的重新渲染, 虽然对用户不可见,但是会影响组件的性能。 如果你试图将某些 state(状态) “镜像”到来自上面的 属性(props) 中, 请考虑直接使用 属性(props) 。 阅读更多关于 为什么将 属性(props) 复制到 state(状态) 会导致错误 。
/*
该方法unsafe 避免使用
//判断props是否发生变化该
componentWillReceiveProps(nextProps){
if(nextProps.params.bg !== this.props.params.bg){
let query = {bg:nextProps.params.bg};
this.props.dispatch(searchAuthorities(query));
}
}
*/
/*
判断props是否发生变化
*/
componentDidUpdate(prevProps) {
if (this.props.params.bg !== prevProps.params.bg) {
let query = {bg:this.props.params.bg};
this.props.dispatch(searchAuthorities(query));
}
}
3.卸载