React Hooks - 即使状态没有改变,useEffect 也会触发

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: [...]