【问题标题】:Handling useEffect处理 useEffect
【发布时间】:2021-04-07 05:08:09
【问题描述】:
const UserProfile = ({
  user=[],
}) =>{ 
  useEffect(() => {
    console.log("mounted")
    console.log("inside: "+user.id)
  },[]);
  
  console.log("outside :"+user.id)
   return(
    <Text>hello</Text>
  );
};

为什么这会返回此日志? 我认为 useEffect 中的 user.id 应该返回相同的

【问题讨论】:

    标签: react-native use-effect


    【解决方案1】:

    试试这个:

    useEffect(() => {
      if (!user.id) {
        return
      }
      console.log("mounted")
      console.log("inside: "+user.id)
    },[user])
    

    【讨论】:

      【解决方案2】:

      你的效果只会被调用一次,在挂载时。正如您在日志中看到的那样(outside :undefinedinside: undefined),在安装时没有设置 user 值。然后,当你将userid 传递给UserProfile 组件时,不会调用效果,因为使用空依赖数组注册效果表明它只会在挂载时调用。

      请查看:https://reactjs.org/docs/hooks-effect.html (最后一个黄色注释部分)

      如果您希望每次user 属性更改时都调用您的效果,请将其添加到依赖关系数组中,如下所示:

      useEffect(() => {
      ...
      },[user])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-22
        • 2020-10-10
        • 2020-11-29
        • 1970-01-01
        • 1970-01-01
        • 2023-01-08
        • 2021-12-24
        相关资源
        最近更新 更多