【发布时间】:2021-09-10 03:29:00
【问题描述】:
我正在尝试实现此逻辑以有条件地从 API 中获取,我在 useEffect 挂钩中创建了获取逻辑,但我无法在我的组件中调用它们。 这样做的正确方法是什么。 或者我还有什么其他方法可以做到这一点?
对于 getF1、GetF2、getF3 函数,我使用了 try-catch 块,没有显示完整的代码
const myComponent = () => {
const [info, setInfo] = useState([]);
let venueName;
let cId;
useEffect(() => {
const getTData = async (tid) => {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.error(error);
}
};
const getCC = async (tid) => {
const t2data = await getTData(tid);
cId = t2data?.xyz;
console.log(cId);
};
getCC(tid);
async function getF1() {
const response = await fetch(url1);
}
async function getF2() {
const response = await fetch(url2);
}
async function getF3() {
const response = await fetch(url3);
}
getF1();
}, []);
const mainF = () => {
let res1 = info.filter((x) => x.fields.travelId == tid);
if (res1.length != 0) {
linkValue =
res1[0].a != undefined
? res1[0].a
: res1[0].b != undefined
? res1[0].b
: getF2();
let res2 = info.filter(
(x) => x.fields.colorId == cId
);
if (res2.length != 0) {
linkValue =
res2[0].a != undefined
? res2[0].a
: res2[0].b!= undefined
? res2[0].b
: getF3();
let res3 = info.filter((x) => x.fields.venue == venueName);
if (res3.length != 0) {
linkValue =
res3[0].a != undefined
? res3[0].a
: "www.google.com";
}
}
}
return linkValue;
};
let finalValue = mainF();
【问题讨论】:
-
在 useEffect 之外创建函数,然后从 useEffect 内部调用。像这样 useEffect(() => { getCC(tid); getF1(); },[]) 另外,不确定,但我认为你需要在 state 中存储场地名称、cId。
-
我也应该在 useEffect 之外制作 getF2、getF3 吗?我在 mainF(); 内有条件地调用它们;
-
是的,您可以尝试使用它。否则我认为它会出现编译错误,例如未定义函数。
标签: reactjs react-hooks fetch jsx use-effect