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

ReactJS问题:FetchPlayers提前执行致编辑后页面未更新

你的推测完全正确!问题核心在于**fetch是异步操作**——当你在Btn_EditPlayer里连续调用this.edit_player()和this.FetchPlayers()时,获取玩家列表的请求并不会等编辑请求完成再执行,它会立刻发起,这时候后端的模拟数据库还没完成修改,所以拿到的还是旧数据,自然页面不会更新,必须手动刷新才能看到新内容。

下面是具体的解决方案:

第一步:让edit_player返回Promise

现在你的edit_player函数没有返回任何值,我们需要让它返回fetch生成的Promise,这样才能追踪编辑请求的完成状态:

edit_player(_playerid, _newfirstname, _newlastname, _newclass) {
  // 关键:加上return,把fetch的Promise返回出去
  return fetch('http://' + Globals.BaseIP + Globals.PortForBackend + '/api/editplayer', {
    method:'POST',
    headers: {
      'Accept':'application/json, text/plain, */*',
      'Content-type':'application/json'
    },
    body:JSON.stringify({
      UserID:UserServiceLocal.UserID(), 
      token:UserServiceLocal.token(), 
      GameID:this.props.gameID, 
      PlayerID:_playerid, 
      Firstname:_newfirstname, 
      Lastname:_newlastname, 
      Class:_newclass
    }),
    mode:'cors'
  })
  .catch((error) => {
    console.log(error);
    throw error; // 把错误抛出,让调用方可以捕获处理
  });
}

第二步:等待编辑完成后再刷新列表

修改Btn_EditPlayer,利用Promise的.then()方法,确保只有当编辑请求成功完成后,才调用FetchPlayers获取最新数据:

Btn_EditPlayer() {
  this.edit_player(
    this.state.playereditID, 
    this.state.playereditName, 
    this.state.playereditLastname, 
    this.state.playereditClass
  )
  .then(() => {
    // 编辑请求彻底完成后,再获取最新玩家列表
    this.FetchPlayers();
  })
  .catch((err) => {
    // 这里可以添加编辑失败的提示,比如给用户弹个错误框
    console.error('编辑玩家失败:', err);
  });
}

进阶:用async/await让代码更易读

如果你习惯更直观的同步写法,可以把Btn_EditPlayer改成异步函数,逻辑会更清晰:

async Btn_EditPlayer() {
  try {
    // 等待编辑请求完成
    await this.edit_player(
      this.state.playereditID, 
      this.state.playereditName, 
      this.state.playereditLastname, 
      this.state.playereditClass
    );
    // 编辑成功后刷新列表
    this.FetchPlayers();
  } catch (err) {
    console.error('编辑玩家失败:', err);
  }
}

额外优化:校验后端响应状态

为了避免后端编辑失败时仍刷新列表,建议在edit_player里加上响应状态校验:

edit_player(_playerid, _newfirstname, _newlastname, _newclass) {
  return fetch('http://' + Globals.BaseIP + Globals.PortForBackend + '/api/editplayer', {
    // 原有的配置...
  })
  .then(res => {
    // 检查HTTP响应状态是否成功
    if (!res.ok) {
      throw new Error(`请求失败:${res.status}`);
    }
    return res.json(); // 如果后端返回了结果,可以在这里处理
  })
  .catch((error) => {
    console.log(error);
    throw error;
  });
}

这样修改后,页面就能在编辑完成后自动显示最新的玩家信息,不需要手动刷新了。

内容的提问来源于stack exchange,提问作者Ben10

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:26:24