【问题标题】:Why React Component class and functionnal component does not have the same behaviour?为什么 React Component 类和功能组件没有相同的行为?
【发布时间】: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 />;
}

有人有想法吗?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您好,如果我能很好地理解您的问题,这里是您问题的解决方案 https://codesandbox.io/s/crazy-wave-cj2n3?fontsize=14&hidenavigation=1&theme=dark 并解释代码中的问题 当道具(可见)更改时,您不会告诉子组件重新渲染,并且您需要将其传递到 useEffect 函数的数组中 如果您想了解更多取消注释 App 组件中的行并从 useEffect 中删除可见 您会看到状态实际上是在父级中从 true 变为 false 而在子级中没有

【讨论】:

    猜你喜欢
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多