首页 > 解决方案 > 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]) 

标签: reactjsreact-nativereact-hooks

解决方案


你可以这样做。

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 执行相同的操作。


推荐阅读