为什么即使依赖关系没有改变,useEffect 也会在页面重新加载时触发?

Why does useEffect fires on page reload even when the dependency is not changing?

我的一个 React 组件中有这个 useEffect。

const [photo,setPhoto]=useState();

useEffect(()=>{
    console.log("inside photo useEffect")
    setIsLoading(true);

    fetch("/uploadPhoto",{
        method:"post",
        body:photo
    })
    .then(res=>res.json())
    .then(data=>{
        setPhotoURL(data.secure_url);
        setIsLoading(false)
    })
    .catch(err=>{
        console.log(err);
    })
},[photo])

我只想在“photo”的值发生变化时触发这个 useEffect。但是只要重新加载页面,它就会被触发。

如何实现?

我找到了一种方法来做到这一点。 似乎 useEffect 默认情况下会在每个渲染器上执行,而不管依赖性如何。我们使用依赖项作为第二个参数来定义何时应再次执行 useEffect。

我像这样更改了我的代码并且成功了。

useEffect(()=>{
    if(photo){ 
        console.log("inside photo useeffect")
        setIsLoading(true);
        

        fetch("/uploadPhoto",{
            method:"post",
            body:photo
        })
        .then(res=>res.json())
        .then(data=>{
            setPhotoURL(data.secure_url);
            setIsLoading(false)
        })
        .catch(err=>{
            console.log(err);
        })
    }
},[photo])

仅当“photo”有值时才会执行。