React 功能组件中的依赖 api 调用

Dependent api call in React functional component

所以我有一个功能组件,可以调用 API 来获取 "player" json 对象。在那个获取的 "player" 对象中,我有一个嵌套的 "team" 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 调用,但在该调用中,第一个 API 调用尚未设置 team_id。任何想法都会很棒,谢谢!!

发现您可以将值添加到 "listen" 的第二个参数。对该值的更改将调用它所绑定的 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 调用提取。