Reactjs 对依赖数据项进行本机获取和使用usestate作出反应
我试图从3个API中获取3个相关数据项。我的意思是,我获取元素a,b和c,c依赖于b,b依赖于a。当我获取数据时,我需要在获取下一个数据之前首先检查它是否为null,然后如果它为null,我会再次尝试获取它,或者获取下一个数据项。现在,我在实现这一点上遇到了问题。我使用useState将项目“a”存储在一个状态中,然后奇怪的事情发生了。例如,当数据在“a”中更新时,它将变为null,然后获取有效数据,然后再次变为null。因此,当我获取“b”时,我无法确定“a”是否为null 我尝试使用useffect来确保状态被更新,但仍然会出现奇怪的行为Reactjs 对依赖数据项进行本机获取和使用usestate作出反应,reactjs,react-native,react-hooks,Reactjs,React Native,React Hooks,我试图从3个API中获取3个相关数据项。我的意思是,我获取元素a,b和c,c依赖于b,b依赖于a。当我获取数据时,我需要在获取下一个数据之前首先检查它是否为null,然后如果它为null,我会再次尝试获取它,或者获取下一个数据项。现在,我在实现这一点上遇到了问题。我使用useState将项目“a”存储在一个状态中,然后奇怪的事情发生了。例如,当数据在“a”中更新时,它将变为null,然后获取有效数据,然后再次变为null。因此,当我获取“b”时,我无法确定“a”是否为null 我尝试使用usef
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])
您可以对第3项执行相同的操作