You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 11:51:03