处理useEffect
Handling useEffect
const UserProfile = ({
user=[],
}) =>{
useEffect(() => {
console.log("mounted")
console.log("inside: "+user.id)
},[]);
console.log("outside :"+user.id)
return(
<Text>hello</Text>
);
};
为什么要 return 写入此日志?
我认为useEffect中的user.id应该return一样
试试这个:
useEffect(() => {
if (!user.id) {
return
}
console.log("mounted")
console.log("inside: "+user.id)
},[user])
您的效果在挂载时仅调用一次。在安装时没有设置 user
值,如您在日志中所见(outside :undefined
和 inside: undefined
)。然后,当您将 user
和 id
传递给 UserProfile
组件时,不会调用 effect,因为使用空依赖数组注册 effect 表明它只会在挂载时调用。
请检查:https://reactjs.org/docs/hooks-effect.html
(最后一个黄色音符部分)
如果您希望每次 user
属性 更改时都调用您的效果,请将其添加到依赖项数组,如下所示:
useEffect(() => {
...
},[user])
const UserProfile = ({
user=[],
}) =>{
useEffect(() => {
console.log("mounted")
console.log("inside: "+user.id)
},[]);
console.log("outside :"+user.id)
return(
<Text>hello</Text>
);
};
为什么要 return 写入此日志? 我认为useEffect中的user.id应该return一样
试试这个:
useEffect(() => {
if (!user.id) {
return
}
console.log("mounted")
console.log("inside: "+user.id)
},[user])
您的效果在挂载时仅调用一次。在安装时没有设置 user
值,如您在日志中所见(outside :undefined
和 inside: undefined
)。然后,当您将 user
和 id
传递给 UserProfile
组件时,不会调用 effect,因为使用空依赖数组注册 effect 表明它只会在挂载时调用。
请检查:https://reactjs.org/docs/hooks-effect.html (最后一个黄色音符部分)
如果您希望每次 user
属性 更改时都调用您的效果,请将其添加到依赖项数组,如下所示:
useEffect(() => {
...
},[user])