理解React组件生命周期
简介在使用 接下来,这篇文章会讲一讲这些生命周期的方法是何时被执行的。 理解组件的生命周期,当组件被创建或销毁时,可以执行某些操作。此外,当 生命周期为了清楚的了解生命周期,我们需要明白 组件初始化 , 组件初始化
constructor()
构造函数是初始化状态的合适位置。若你不初始化状态且不绑定方法,那你也不需要为你的React组件定义一个构造函数。 可以基于属性来初始化状态。这样有效地“分离(forks)”属性并根据初始属性设置状态。这有一个有效的 constructor(props) { super(props); this.state = { color: props.initialColor }; } componentWillMount()componentWillMount()
这是唯一的会在服务端渲染调起的生命周期钩子函数。通常地,我们推荐使用 render()
当被调用时,其应该检查
当返回 注意 componentDidMount()componentDidMount()
State Changes
shouldComponentUpdate()shouldComponentUpdate(nextProps,nextState) 使用 当接收到新属性或状态时, 当他们状态改变时,返回
注意:如果只定义方法,不写任何返回值,会提示:
注意即使属性未有任何改变, 在装配期间,React并不会调用带有初始属性的 componentWillUpdate()componentWillUpdate(nextProps,nextState) 当接收到新属性或状态时, 注意你不能在这调用 注意:若shouldComponentUpdate()返回false,componentWillUpdate()将不会被调用。 componentDidUpdate()componentDidUpdate(nextProps,nextState) 当接收到新属性或状态时, 注意:你不能在这调用 Props Changes
componentWillReceiveProps()componentWillReceiveProps(nextProps)
注意:即使属性未有任何改变,
在装配期间, Unmounting
componentWillUnmount()componentWillUnmount()
forceUpdate
默认情况,当你的组件或状态发生改变,你的组件将会重渲。若你的 调用 通常你应该尝试避免所有 forceUpdate() Example// forceUpdate() Example class App extends React.Component{ constructor(){ super(); this.forceUpdateHandler = this.forceUpdateHandler.bind(this); }; componentWillUpdate() { console.info('componentWillUpdate called'); } componentDidUpdate() { console.info('componentDidUpdate called'); } forceUpdateHandler(){ this.forceUpdate(); }; render(){ return( <div> <button onClick= {this.forceUpdateHandler} >FORCE UPDATE</button> <h4>Random Number : { Math.random() }</h4> </div> ); } } ReactDOM.render(<App />,document.getElementById('app')); 原文链接 参考资源react component lifecycle:https://busypeoples.github.io... react 官方文档:https://doc.react-china.org/d... forceUpdate() Example:https://codepen.io/SyedAfrozP... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- c# – 来自DataTrigger的WPF调用方法
- [前端]react:ant-design的demo
- ruby-on-rails – Capistrano部署但手动运行迁移
- 语言无关 – 在使用域模型和POCO类时,查询在哪里?
- 设计模式:单一职责原则
- AJAX 的DragPanelExtender 拖曳控件使用,并保存位置(此方法
- 构建过程 – Makefile生成器:premake vs bakefile?
- ibm-mobilefirst – IBM Worklight JSONStore |从集合中删除
- ruby-on-rails – 使用Rails运行多个后台并行作业
- dojo/dom-construct的create方法