首页 > 解决方案 > 无法链接 useEffects 以使用来自先前效果的更新状态

问题描述

我有一个具有一些复杂数据获取的应用程序。总的来说,这是我的应用程序中的逻辑快照

// dep1 is from redux, dep2 is local state

// useEffect 1
useEffect(() => {
   // perform some state variable update to dep2
}, [dep1]);

// useEffect 2
useEffect(() => {
   // use some values from deps to fetch data
}, [dep1, dep2]);

我面临的问题是,当 dep1 和/或 dep2 更新时,useEffect 1 的状态更改需要反映在 useEffect 2 中数据获取操作的请求 url 中。useEffect 2 最终运行两次,一次是使用 dep1 更新(没有来自 url 中 useEffect 1 的 dep2 更新)和一次有 dep2 更新。在我们只是渲染的大多数情况下,这个问题并不特别明显,但在 useEffect 中使用数据获取的情况下,我们最终会出现双 api 获取。我可以使用什么策略来规避这种双重 API 调用?

编辑 添加更多代码以允许更具体的问题:

// useEffect 1
// when the user is changed (user is a prop that is from redux),
// option should be reset to "DEFAULT"
useEffect(() => {
    setOption("DEFAULT");
}, [currentUser]);

// useEffect 2
// option is a value that can be set within the UI and is local state.
// setting option to a new value will trigger api call with new value
useEffect(() => {
    const data = await getData(option);
}, [currentUser, option]);

The issue when option is not "DEFAULT" and currentUser changes, useEffect 2 will run twice. 如果 currentUser 更改,我想找到一些逻辑以允许它运行一次,并将选项设置回“DEFAULT”。这是否可以使用其他反应模式,因为使用 useEffect 似乎不可能?

标签: javascriptreactjsreact-hooksclosuresuse-effect

解决方案


尝试在当前组件中的 react 组件中设置 dep2 并将其作为 prop 传递,这样每个组件中只有一个 useEffect ,并且状态被向上传递。

const component = () => {

    useEffect(() => {
       // do something
    }, [dep1]);
    
    
    return (
           <div> <ComponentTwo depTwo={depTwo}/> </div>
    )
}

然后在 ComponentTwo ...

const componentTwo = ({ depTwo }) => {

    // useEffect 2
    useEffect(() => {
       // use some values from deps to fetch data
    }, [dep2]);
    
    
    return (<div> something </div>
    
    )
}

您需要在父组件中导入 ComponentTwo。


推荐阅读