class Clock extends React.Component {
state = { time: new Date().toLocaleTimeString() };
componentDidMount() {
setInterval(() => {
this.setState = ({ time: new Date().toLocaleTimeString()})
}, 1000)
}
render() {
return (
<div className="time">
the time is :{this.state.time}
</div>
);
}
};
这是一个简单的时钟响应应用程序,其中ComponentDidMount不起作用
答案 0 :(得分:0)
setState
是一个功能:
this.setState({ time: new Date().toLocaleTimeString()})
setState()
使对组件状态的更改排队,并告知React该组件及其子级需要以更新后的状态重新呈现。
答案 1 :(得分:0)
setState是一个函数,应调用而不是分配它。也不要忘记删除卸载计时器,以防止内存泄漏 这是工作示例
答案 2 :(得分:0)
好吧,setState将调用该组件的某些生命周期,重新渲染它,然后重新渲染该组件的所有子代 顺便说一下,这是一个有效的例子 https://codesandbox.io/s/blazing-resonance-kjoyi
import React, { Component } from "react";
class Clock extends Component {
constructor(props) {
super(props);
this.state = {
time: null
};
this.handleSetTime = this.handleSetTime.bind(this);
this.timer = null;
}
componentDidMount() {
this.handleSetTime();
this.timer = setInterval(this.handleSetTime, 1000);
}
handleSetTime() {
this.setState({
time: new Date().toLocaleTimeString()
});
}
render() {
const { time } = this.state;
return <div className="time">the time is:{time}</div>;
}
componentWillMount() {
clearInterval(this.timer);
this.timer = null;
}
}
export default Clock;
我建议您使用ref选择一个dom元素并每秒对其进行更新,这样一来,就不会进行任何重新渲染,并且由于它将成为无状态组件,因此它甚至会具有更好的性能。
这是一个带参考的有状态示例 https://codesandbox.io/s/still-framework-xxxeg
import React, { Component, createRef } from "react";
class Clock extends Component {
constructor(props) {
super(props);
this.ref = createRef();
this.timer = null;
this.handleUpdateTimer = this.handleUpdateTimer.bind(this);
}
componentDidMount() {
this.handleUpdateTimer();
this.timer = setInterval(this.handleUpdateTimer, 1000);
}
handleUpdateTimer() {
this.ref.current.innerText = new Date().toLocaleTimeString();
}
render() {
return (
<div className="App">
time is: <span ref={this.ref} />
</div>
);
}
componentWillUnmount() {
clearInterval(this.timer);
this.timer = null;
}
}
export default Clock;
最后,最好的,也是使用钩子的无状态组件 https://codesandbox.io/s/silent-leftpad-cc4mv
import React, { useRef, useEffect } from "react";
const Clock = () => {
const ref = useRef();
useEffect(() => {
setTimer();
const timer = setInterval(setTimer, 1000);
return () => {
clearInterval(timer);
};
}, []);
const setTimer = () => {
ref.current.innerText = new Date().toLocaleTimeString();
};
return (
<div className="App">
time is : <span ref={ref} />
</div>
);
};
export default Clock;