如何在两个钩子之间调用if语句



在我的项目中,我使用useState&使用Effect从API获取数据。现在假设,根据我的场景,我有2个API来获取数据。第一个API使用获取id,使用id获取第二个API。

正如大家所知,使用useEffect获取API在某些情况下,首先渲染它给出的是undefine和它给出的数据,所以我尝试使用if语句来避免undefine,以避免第一个API的undefine。但是,当我在一个项目中使用2个钩子时,我不能在第一个钩子之后使用if语句。如果在两个钩子的末尾都使用it,则if语句不能正常工作。在这种情况下,当我在一个项目中使用两个钩子时,我应该在哪里使用if语句。第一个钩子的where if语句有效。

假设,我的代码在这里:

import React, { useEffect, useState } from 'react';
import View from 'react-native';

export default function MyComponent() {
const [data, setData] = useState();
const [loc, setLoc] = useState([]);

useEffect(() => {
fetch(
'https://www.roads.com/road/api/auth/web/roadControl?projectId=765&pageSize=150')
.then((response) => response.json())
.then((data) => setData(data.id))
.catch((error) => console.error(error));
}, []);
if (!data) return null;
async function fD() {
try {
const rA = await Promise.all(
data?.map((id) => {
const nfo= fetch(`https://www.roads.com/road/web/roadControl/${id}`)
.then((response) => response.json())
.then((a) => {
return a;
})
.catch((error) => console.error(error));
return nfo;
})
);
setLoc(rA);
} catch (error) {
console.log(error);
}
}
useEffect(() => {
fD();
});
}

在这种情况下,我应该在哪里使用if语句作为第一个钩子。

在此处输入图像描述

我认为您可以尝试将fD()放在useEffect钩子中的then块中。事实上,我不认为useState挂钩是存储数据所必需的。

useEffect(() => {
fetch(
'https://www.roads.com/road/api/auth/web/roadControl?projectId=765&pageSize=150')
.then((response) => response.json())
.then((data) => fD(id) // passing id to the function as parameter)
.catch((error) => console.error(error));
}, []);

最新更新