【发布时间】:2020-10-31 17:24:10
【问题描述】:
我正在使用 React 17,我想知道为什么以下组件的行为不一样。 使用 react 组件类时,方法内部的 props 会更新,而使用功能组件时,它们不会。
使用 React.Component 类(可见道具在检查方法中更新)
class Clock extends React.Component {
constructor(props) {
super(props);
}
check() {
console.log(this.props.visible);
}
componentDidMount() {
this.timerID = setInterval(
() => this.check(),
5000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
render() {
return (
<div />
);
}
}
使用带有钩子的函数(可见道具不会在检查方法中更新)
function Comp(props) { // contains visible attr (false by default)
const check = () => {
console.log(props.visible); // stays as the default value when Comp mounted
};
useEffect(() => {
const timerId = setInterval(() => {
check();
}, 5000);
return () => clearInterval(timerId);
}, []);
return <div />;
}
有人有想法吗?
【问题讨论】:
-
是的,陈旧的闭包 - 上面的答案是 setInterval 的特定情况,例如我在stackoverflow.com/a/58877875/1176601 中的回答包含更多技术细节
标签: javascript reactjs