React 功能组件中的依赖 api 调用 [英] Dependent api call in React functional component
问题描述
所以我有一个功能组件,它进行 API 调用以获取玩家"json 对象.在提取的玩家"对象中,我有一个嵌套的团队"json 对象,其中包含我需要在单独的 API 调用中使用的 ID.由于 API 调用的性质是异步的,我如何保证第二个 API 调用会起作用.
So I have a functional component that makes an API call to get a "player" json object. In that fetched "player" object, I have a nested "team" json object that contains an id that I need to use in a separate API call. Since the nature of API calls are asynchronous, how can I guarantee the second API call will work.
const [player, setPlayer] = useState({});
async function fetchPlayer() {
const res = await fetch(baseUrl + "/Players/" + player_id);
res
.json()
.then(res => setPlayer(res));
}
useEffect(() => {
fetchPlayer();
}, []);
const {
firstname = " ",
lastname = " ",
team
} = player;
const {
name = " ",
team_id = 0
} = team || {};
// what I want to do. Team_id isn't set however...
const [thing, SetThing] = useState({});
async function fetchThing() {
const res = await fetch(baseUrl + "/Thing/" + team_id);
res
.json()
.then(res => setThing(res));
}
基本上我已经能够获取团队 json 对象,它是 team_id,但我不确定如何实现另一个依赖于团队 id 的 API 调用.
Basically I'm already able to get the team json object and it's team_id but I'm not sure how I can implement another API call that depends on team id.
我已经尝试添加另一个异步函数来容纳第二个 API 调用,但在该调用中,第一个 API 调用尚未设置 team_id.任何想法都会很棒,谢谢!!
I've tried just adding another async function to house the second API call but inside that call, team_id has not yet been set by the first API call. Any ideas would be great, thanks!!
推荐答案
发现您可以为第二个参数添加值以收听".对该值的更改将调用它所关联的 useEffect.例如我添加了这个:
Found out that you could add value to the second argument to "listen" to. Changes to that value will call that useEffect it's tied to. For example I added this:
const [thing, setThing] = useState({});
async function fetchThing() {
const res = await fetch(baseUrl + "/Thing/" + team_id);
res
.json()
.then(res => setThing(res));
}
useEffect(() => {
fetchThing();
}, [team_id]);
所以现在上面的 useEffect 会在 team_id 改变时触发.因此,可以保证设置了 team_id,然后 useEffect 使用我们在第一次 API 调用中等待的新 team_id 调用获取.
So now the useEffect above will trigger when team_id changes. So it's guaranteed that team_id is set and then the useEffect calls the fetch with the new team_id that we were waiting for from the first API call.
这篇关于React 功能组件中的依赖 api 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!