javascript - 无法链接 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 似乎不可能?
解决方案
尝试在当前组件中的 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。
推荐阅读
- c - 在visual studio代码上设置“Per Monitor DPI Aware”?
- reactjs - 有没有办法将变量值从一个反应组件传递到另一个?
- c# - IIS .NET Core 5.0 MVC API - 出现 HTTP 错误 500.30 - ASP.NET Core 应用程序无法启动
- cypress - 赛普拉斯有没有办法检查开放请求?
- python - 返回值和跟踪内部状态时如何使用 Python super()?
- installation - 使复选框的行为类似于单选按钮,但默认选择其中一个部分 - NSIS 组件页面
- bash - 如何使 apt 假设是并强制 bash 脚本中的所有安装是
- python - 在一个非常大的表上对 Google Cloud SQL 的超慢 SQLAlchemy 查询
- amazon-cloudformation - 如何使用 AWS CloudFormation 模板更正此错误
- javascript - 如何使用新文件中的内容更改网页上的 SVG 元素?