我正在使用 React 17,我想知道為什么以下組件的行為不一樣。當使用 React 組件類時,方法內的 props 會被更新,而使用功能組件時,它們不會更新。使用 React.Component 類(可見 props 在 check 方法內更新)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 />;}有人有想法嗎?
為什么 React Component 類和函數組件沒有相同的行為?
互換的青春
2023-06-29 15:49:02