首页 > 解决方案 > React 功能组件中的依赖 api 调用

问题描述

所以我有一个功能组件,它通过 API 调用来获取“播放器”json 对象。在那个获取的“玩家”对象中,我有一个嵌套的“团队”json 对象,其中包含我需要在单独的 API 调用中使用的 id。由于 API 调用的性质是异步的,我如何保证第二个 API 调用能够正常工作。

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 调用。

我尝试添加另一个异步函数来容纳第二个 API 调用,但在该调用中,team_id 尚未由第一个 API 调用设置。任何想法都会很棒,谢谢!

标签: reactjsapireact-functional-component

解决方案


发现您可以为“听”的第二个参数添加值。对该值的更改将调用它所绑定的 useEffect。例如我添加了这个:

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 调用 fetch。


推荐阅读