小能豆

为什么我在 React 中收到一个空字符串作为数据?

javascript

我试图将字符串 id 传递给位于另一个文件中的函数,但作为该函数的响应,我得到的只是一个空字符串。如果再次调用该函数,则会显示 ID。我所说的函数位于第二个 .then - getMatchHistory() 中。这是我的代码:

  axios
      .get(`https://${region}.api.riotgames.com/lol/summoner/v4/summoners/by-name/${summonerName}?api_key=${API_KEY}`)
      .then((response) => {
        setError("");
        setUser(response.data);
        setName(response.data.name);
        setProfileIcon(response.data.profileIconId);
        setLevel(response.data.summonerLevel);
        setPuuid(response.data.puuid);
        setSummonerName("");
        console.log("Hello from GetUser.jsx");
      })
      .then(() => {
        getMatchHistory(puuid);
      })
      .catch(() => {
        setError("There is no summoner with that name!");
        setSummonerName("");
        setUser("");
      });

现在,我用简单的 console.log() 链接了多个 .then ,它们以正确的顺序依次显示,但在这里它不起作用 - 只是传递一个空字符串。


阅读 114

收藏
2024-02-28

共1个答案

小能豆

根据代码访问第二个 .then() 中的 puuid 的方式是获取在第一个 .then() 中设置的状态 puuidsetPuuid(response.data.puuid);问题是,react 中的状态更新是异步的,因此在访问第二个 .then() 中的状态,状态尚未更新。

要修复,有几个选项

  1. 从第一个函数返回 puuid 并在第二个函数中接受作为参数
axios
      .get(`https://${region}.api.riotgames.com/lol/summoner/v4/summoners/by-name/${summonerName}?api_key=${API_KEY}`)
      .then((response) => {
        setError("");
        setUser(response.data);
        setName(response.data.name);
        setProfileIcon(response.data.profileIconId);
        setLevel(response.data.summonerLevel);
        setPuuid(response.data.puuid);
        setSummonerName("");
        console.log("Hello from GetUser.jsx");
        return response.data.puuid;//return the value
      })
      .then((puuid) => {//accept it as a param
        getMatchHistory(puuid);
      })
      .catch(() => {
        setError("There is no summoner with that name!");
        setSummonerName("");
        setUser("");
      });
  1. 根据您想要执行的操作,您始终可以将 getMatchHistory 调用移至第一个 .then
 getMatchHistory(response.data.puuid);
  1. 在更新 puuid 状态时运行的 useEffect 中包含 getMatchHistory
2024-02-28