【问题标题】:What is the difference between console.log("render") and React.useEffect(()=>console.log("render")) in functional component功能组件中的console.log("render")和React.useEffect(()=>console.log("render"))有什么区别
【发布时间】:2020-05-10 13:17:34
【问题描述】:

如果我有这样的功能组件:

const Example = ({props})=> {
    console.log("render outside effect");
    React.useEffect(()=>console.log("render inside effect"))
}

这两个调用有什么区别?

这与我对功能性反应组件的理解相同。该函数将在每次重新渲染时执行,所以 useEffect 之外的所有表达式和函数都将被执行?!不带括号的 useEffect 也会在每次重新渲染时执行?

这是误会吗?

提前致谢

特里斯坦

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    一旦渲染周期为组件,函数组件内的useEffect就会被调用

    组件中的两个控制台日志肯定会在每次重新渲染时被调用。但是 useEffect console.log 将在 react 完成 DOM 的绘制后重新渲染,但是直接在功能组件内部的 console.log() 将在 DOM 渲染完成之前执行

    react 中的useEffects 用于基于state or props 运行subscriptionssideEffects,就像React class components 中的生命周期方法一样

    您可以使用dependency 参数控制何时执行useEffect

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 2022-11-22
      相关资源
      最近更新 更多