React Native开发:useState设置summonerId后fetchId2读取为null如何解决
问题根因
- React 的
useState更新是异步批量执行的,你在fetchId1的回调里调用setSummonerId之后,当前作用域里的summonerId还是本次渲染周期的旧值(也就是初始的 null),不会立刻变成新值 - 你的
Url2是组件初始化/每次渲染时提前计算的,本次渲染周期里summonerId为 null,所以Url2拼接的时候就是用的 null 值,即使你调用setSummonerId之后马上调用fetchId2,用的还是旧的Url2
修复方案
方案1:直接传参调用(推荐,改动最小)
直接把接口返回的summonerId作为参数传给fetchId2,不依赖状态里的旧值:
// 修改fetchId2,接收summonerId作为入参 const fetchId2 = (sid) => { // 调用请求时实时拼接url,不用提前计算的Url2 const currUrl2 = url2 + sid + "?api_key=" + apikey; fetch(currUrl2) .then((response) => response.json()) .then((responseJson2) => { console.log(responseJson2); return responseJson2; }) .catch((error) => { console.log(sid); console.error(error); }); }; // 修改fetchId1里的调用逻辑 const fetchId1 = () => { fetch(Url1) .then((response) => response.json()) .then((responseJson) => { setName(responseJson.name); setSummonerLevel(responseJson.summonerLevel); setSummonerId(responseJson.summonerId); setAccountId(responseJson.accountId); setAccountPuuid(responseJson.accountPuuid); setProfileIcon(responseJson.profileIconId); console.log(responseJson); // 直接传接口返回的summonerId fetchId2(responseJson.summonerId); return responseJson; }) .catch((error) => { console.error(error); setName("Player Not Found!"); setSummonerLevel("N/A"); setAccountId("N/A"); }); };
方案2:通过useEffect监听触发
如果你的fetchId2需要在summonerId更新后自动执行,可以用监听逻辑:
// 首先引入useEffect import React, { useState, useEffect } from "react"; // 组件内添加监听逻辑 useEffect(() => { // 只有summonerId有有效值时才发起请求 if (summonerId) { fetchId2(); } }, [summonerId]) // 修改fetchId2,实时拼接url const fetchId2 = () => { const currUrl2 = url2 + summonerId + "?api_key=" + apikey; fetch(currUrl2) .then((response) => response.json()) .then((responseJson2) => { console.log(responseJson2); return responseJson2; }) .catch((error) => { console.log(summonerId); console.error(error); }); }; // 去掉fetchId1里手动调用fetchId2的代码即可
小提示:建议不要提前在组件顶层拼接
Url1和Url2,最好在发起对应请求的时候再拼接url,避免出现使用旧状态值的问题。
内容的提问来源于stack exchange,提问作者StanLachie
相关产品推荐
相关产品推荐

