【问题标题】:How can I ensure that a line of code is executed only once using React hooks in a functional component?如何确保在功能组件中使用 React 钩子只执行一次代码?
【发布时间】:2020-11-24 19:49:24
【问题描述】:

我希望 React 组件中的一行代码仅在安装组件时执行,而不是在重新渲染时执行。在有状态组件中,我会在 componentDidMount/componentWillMount 方法中执行此操作。

如何使用钩子来做到这一点?

【问题讨论】:

    标签: reactjs react-hooks react-functional-component


    【解决方案1】:

    // 类似于componentDidMount和componentDidUpdate: useEffect(() => {}, [])

    反应文档。 Hooks - 使用 Effect Hook。 - > https://reactjs.org/docs/hooks-effect.html

    【讨论】:

      【解决方案2】:

      我相信您正在寻找反应 useEffect 钩子。它是 componentDidMount、componentDidUpdate 和 componentWillUnmount 的钩子替换。你可以这样使用它:

      useEffect(() => {
        console.log("only executed once")
      }, [])
      

      注意空数组作为第二个参数,它定义了这个效果的依赖关系。在这种情况下,你希望没有依赖,这样效果就不会再次执行。

      有一篇很好的文章介绍了如何用可用的钩子替换以前的生命周期函数here

      【讨论】:

        猜你喜欢
        • 2023-02-11
        • 2015-08-13
        • 1970-01-01
        • 2021-06-17
        • 2021-03-12
        • 1970-01-01
        • 2017-12-15
        • 2019-09-23
        • 2021-04-13
        相关资源
        最近更新 更多