React中调用getMatchHistory传递PUUID时为何返回空字符串?
问题原因及解决办法
这是因为React的setState是异步批量更新的,你在第一个.then里调用setPuuid(response.data.puuid)后,puuid变量并不会立刻更新成新值,第二个.then执行时拿到的还是原来的空字符串。
两种可行解决方式:
方法一:直接用接口返回的PUUID调用函数
不用依赖状态里的puuid,直接把接口响应里的response.data.puuid传给getMatchHistory,确保拿到的是最新的有效ID:
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"); // 直接使用接口返回的puuid getMatchHistory(response.data.puuid); }) .catch(() => { setError("There is no summoner with that name!"); setSummonerName(""); setUser(""); });
方法二:用useEffect监听PUUID状态变化
如果业务逻辑必须依赖更新后的puuid状态,可以通过useEffect监听puuid的变化,当它从空值变为有效ID时自动调用函数:
// 在组件内部添加useEffect监听 useEffect(() => { // 确保puuid不为空时才执行 if (puuid) { getMatchHistory(puuid); } }, [puuid]); // 仅当puuid变化时触发 // 原axios请求移除第二个.then 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"); }) .catch(() => { setError("There is no summoner with that name!"); setSummonerName(""); setUser(""); });
补充说明
你之前用多个.then调用console.log能按顺序执行,是因为.then本身是按异步流程顺序触发的,但这里的问题不在.then的执行顺序,而在于React状态更新的异步特性——setPuuid调用后,状态不会同步更新,所以后续代码拿不到新值。
内容的提问来源于stack exchange,提问作者Valeri
相关产品推荐
相关产品推荐

