React Hooks - 即使状态没有改变,useEffect 也会触发 [英] React Hooks - useEffect fires even though the state did not change

查看:112
本文介绍了React Hooks - 即使状态没有改变,useEffect 也会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的组件中设置了一个效果,如果另一个状态属性发生变化,它会改变视图.但是由于某种原因,当组件挂载时,即使 detailIndex 的值没有改变,效果也会运行.

I have set up an effect inside my component, which changes the view if another state attribute changes. But for some reason, when the component mounts, the effect is run, even though the value of detailIndex has not changed.

const EventsSearchList = () => {
    const [view, setView] = useState('table');
    const [detailIndex, setDetailIndex] = useState(null);

    useEffect(() => {
        console.log('onMount', detailIndex);
        // On mount shows "null"
    }, []);


    useEffect(
        a => {
            console.log('Running effect', detailIndex);
            // On mount shows "null"!! Should not have run...
            setView('detail');
        },
        [detailIndex]
    );

    return <div>123</div>;

};

为什么会这样?

UPDATE:如果不清楚,我尝试的是在组件更新时运行效果,因为 detailIndex 更改.不是在安装时.

UPDATE: In case it is not clear, what I am trying is to run the effect when the component updates because detailIndex changes. NOT when it mounts.

推荐答案

useEffect 来自 React Hooks 默认在每次渲染时执行,但您可以在函数中使用第二个参数来定义效果何时出现再次被执行.这意味着该函数总是在挂载时执行.在您的情况下,您的第二个 useEffect 将在开始和 detailIndex 更改时运行.

useEffect from React Hooks is by default executed on every render, but you can use second parameter in function to define when the effect will be executed again. That means that function is always executed on mount. In your situation your second useEffect will be run on start and when detailIndex changes.

更多信息:https://reactjs.org/docs/hooks-effect.html

来源:

有经验的 JavaScript 开发人员可能会注意到,传递给 useEffect 的函数在每次渲染时都会有所不同.[...] 如果某些值在重新渲染之间没有改变,你可以告诉 React 跳过应用效果.为此,将数组作为可选的第二个参数传递给 useEffect:[...]

Experienced JavaScript developers might notice that the function passed to useEffect is going to be different on every render. [...] You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect: [...]

这篇关于React Hooks - 即使状态没有改变,useEffect 也会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆