09-10-2021
当组件被初始化,第一次被放入DOM时。
在安装阶段调用的最後一个办法
-constructor
-render()
-componentDidmount()
==在渲染後调用==
import React from 'react';
export class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
render() {
return <div>{this.state.date.toLocaleTimeString()}</div>;
}
componentDidMount() {
const oneSecond = 1000;
this.intervalID=setInterval(() => {
this.setState({ date: new Date() });
}, oneSecond);
}
componentWillUnmount(){
clearInterval(this.intervalID)
}
}
将要改变的 interval ID 存在变数intervalID内
但还不会有作用要与下方的方法和用
this.intervalID=setInterval(() => {
this.setState({ date: new Date() });
}, oneSecond);
将组建移除
在卸载阶段调用,就在组件完全销毁之前
componentWillUnmount(){
clearInterval(this.intervalID)
}
https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
精确模式:
import React from 'react';
export class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
render() {
return (
<div>
{this.props.isPrecise
? this.state.date.toISOString()
: this.state.date.toLocaleTimeString()}
</div>
);
}
startInterval() {
let delay;
if (this.props.isPrecise) {
delay = 100;
} else {
delay = 1000;
}
this.intervalID = setInterval(() => {
this.setState({ date: new Date() });
}, delay);
}
componentDidMount() {
this.startInterval();
}
componentDidUpdate(prevProps) {
if (this.props.isPrecise === prevProps.isPrecise) {
return;
}
clearInterval(this.intervalID);
this.startInterval();
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
}
第一步:创建一个方法 componentDidUpdate(),将渲染後的参数 prevProps 带入
第二步:如果this.props.isPrecise没有改变,现在停止下来,不要做接下来的步骤。
第三步:删除原有的componentWillUnmount()。componentWillUnmount()— 以 开头的单行的正文clearInterval(...。
第四步(目的):开始一个新的间隔。如果在“精确”模式下,它应该每 100 毫秒运行一次。否则,它应该像以前一样每 1000 毫秒运行一次。
componentDidUpdate(prevProps) {
if (this.props.isPrecise === prevProps.isPrecise) {
return;
}
clearInterval(this.intervalID);
this.startInterval();
}
建立新的间隔,在componentDidUpdate()中建立,新的变数为delay,并设置为100 否则为1000。使精确模式更为频繁的更新
并创立一个新的方法:startInterval(),负责计算延迟的时间(100毫秒或是1000毫秒)
并且在componentDidMount() \ componentDidUpdate() 调用他
以下的有使用到此方法的地方都要更换。
startInterval() {
let delay;
if (this.props.isPrecise) {
delay = 100;
} else {
delay = 1000;
}
this.intervalID = setInterval(() => {
this.setState({ date: new Date() });
}, delay);
}
今天简单操作测试Associations 有能力用原生Rspec语法去测任何东西,一定超强的,但是为...
细看 JUCE 框架的设计,可以看到一些 Design Pattern 实例。本文列出几个。 Sin...
graceful shutdown 在关闭服务前,在服务内部以做完该做的事情,使得服务得以善终。 在...
接下来就进到Lab环节了,不过第一个会比较简单,有点像是热热身,熟悉一下python和前後端程序 首...
大家安安 晚上好~~ 今天要把专案里的StatelessWidget 更改成为 StatefulWi...