在讲到生命周期之前要确认理解前面做过的两件事:
以下之前 setInterval 的 example
function tick() {
const element = (
<div> <h1>Hello, world!</h1> <h2>It is {new Date().toLocaleTimeString()}.</h2> </div>
}
);
ReactDOM.render(
element,
document.getElementById('root')
);
setInterval(tick, 1000);
目前这个写法因为 setInterval 是写在最外层,可能造成两个问题
为解决这两个问题,可以做下面三件事:
componentDidMount: 在一个 component 被加入 DOM tree 後,会呼叫执行这个方法
componentDidUpdate: 会在更新後马上被呼叫。这个方法并不会在初次 render 时被呼叫,但要小心更新的资讯应该在限制在某些范围内,例如:子层 update 直接更新父层 props 的来源资料,props 更新又会触动 update , 就产生了程序内回圈。
componentWillUnmount: 会在 component 被 unmount 和 destroy 後马上被呼叫,例如页面移除 component 时。
更多生命周期的细节
以下为结果
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
timeID: null
};
}
componentDidMount() {
this.timeID = setInterval(()=> this.tick(), 1000);
}
componentDidUpdate() {
console.log(this.state.date)
}
componentWillUnmount() {
clearInterval(this.state.timerID);
}
tick() {
this.setState({date: new Date()})
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
(下篇会试着改写 Hook 的写法)
注:Hook 是 React 16.8 中增加的新功能。它让你不必写 class 就能使用 state 以及其他 React 的功能。
参考资料:
https://zh-hant.reactjs.org/docs/components-and-props.html
Class Extend 概念
<<: [重构倒数第12天] - Vue3 directive 与 Skeleton 实战组合应用
既然是从 INFORMIX 剥离出来的工具,应该连结资料库的能力是强大的。本段落我们检视一下Gene...
大家好,我是 A Fei,今天是连假最後一天,虽然正在忙转职根本没有放假的感觉,但看到手机里亲友们一...
今日目标 学习了解 Python Pandas 的观念与运用 What is Pandas? Pan...
工作到现在以来,从乙方公司到成为公司内部的乙方单位,工作的历程比较倾向是用一个个专案堆叠而成。倒数第...
根据昨天的测试我们知道小画家画风的数字模型认不出来,那麽我们可以追加训练让它学习自己画的字。 这次我...