为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 React Component 类和函数组件没有相同的行为?

为什么 React Component 类和函数组件没有相同的行为?

互换的青春 2023-06-29 15:49:02
我正在使用 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 />;}有人有想法吗?
查看完整描述

1 回答

?
达令说

TA贡献1821条经验 获得超6个赞

需要将其传递到 useEffect 函数的数组中,取消注释 App 组件中的行并从 useEffect 中删除可见,您将看到状态实际上在父级中从 true 变为 false,但在子级中却没有。



查看完整回答
反对 回复 2023-06-29
  • 1 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信