【发布时间】:2021-09-24 15:58:29
【问题描述】:
我有一个应用程序有一些复杂的数据提取。总的来说,这是我的应用程序中的逻辑快照
// 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]);
选项不是“DEFAULT”且 currentUser 更改时的问题,useEffect 2 将运行两次。如果 currentUser 更改,我想找到一些逻辑以允许它运行一次,并将选项设置回“DEFAULT”。这是否可能使用其他反应模式,因为它似乎不可能使用 useEffect?
【问题讨论】:
-
要么删除 "dep1" 作为 effect2 的依赖项,要么使用单个效果。您能否更新您的问题以包含更准确/更具代表性的代码示例,以便我们提供更有针对性/准确的帮助?一个正确的解决方案取决于你的具体用例,什么是可能的和有效的。
-
@DrewReese 我已根据要求更新了问题,提供了更多信息
-
如果从 effect2 依赖项中删除
currentUser会发生什么?我不认为它是一个依赖项,因为它没有在钩子回调中引用。当currentUser更改时,它将触发两种效果(因为效果1 更新option以触发效果2)。我确实看到的边缘情况是在初始渲染时,两者都将被调用并会进行第二次getData调用,因此可能会在 effect1 中添加 some 条件以更新选项。
标签: javascript reactjs react-hooks closures use-effect