reactjs - React native 获取和使用 usestate 来获取依赖的数据项
问题描述
我正在尝试从 3 个 API 中获取 3 个相关数据项。我的意思是我获取元素 a、b 和 c,c 依赖于 b,b ia 依赖于 a。当我获取数据时,我需要在获取下一个数据之前首先检查它是否为空,然后如果它为空,我要么尝试再次获取它,要么获取下一个数据项。现在,我在实现这一点时遇到了问题。我使用 useState 将项目“a”存储在一个状态中,然后发生了奇怪的事情。例如,当数据在“a”中更新时,它变为空,然后获取有效数据,然后再次变为空。因此,当我获取“b”时,我无法确定“a”是否不为空。
我尝试使用 useEffect 来确保状态已更新,但我仍然会遇到奇怪的行为。
const [item1, setItem1] = useState(null);
const [item2, setItem2] = useState(null);
useEffect(() =>{
if(item1==null) {
FetchItem1();
}
}, [])
useEffect(() =>{
if(item2==null) {
FetchItem2();
}
}, [item2])
解决方案
你可以这样做。
const [item1, setItem1] = useState(null);
const [item2, setItem2] = useState(null);
useEffect(() =>{
if(item1==null) {
FetchItem1();
// update the result with setItem1()
}
}, [])
useEffect(() =>{
// As item2 is dependant on item1, you need to check whether item1 is there or not null.
if(item1 && item2==null) {
FetchItem2();
// update item2 with setItem2()
}
}, [item1, item2])
您可以对 item3 执行相同的操作。
推荐阅读
- node.js - express.Router() 是否需要导出才能工作?app.use() 的第二个参数似乎无法硬编码,只有在导入时才有效
- node.js - 尝试使用多阶段构建将开发阶段图像与产品阶段构建分开
- javascript - Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length')
- python - 如何在 google colab 中直接从 Yahoo Finance 导入 CSV 文件?
- trino - trino中如何将查询结果导出为csv格式
- javascript - 返回上一页而不是下一个 js 中的上一个 url
- mysql - 选择当月用户信息、房间名称、费用信息
- python - 如何从另一个 py 页面调用 netmiko ConnectHandler 并仅使用选择按钮执行它
- python - 无法使用请求从站点获取表格内容
- reactjs - 如何获取 tr 的 id 并在 reactjs 的 post api 请求正文中使用它