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

React更新功能问题:无法获取数据填充至输入框

React编辑页面无法填充数据的问题修复

问题根源

从报错GET https://localhost:44348/api/Jobs/GetInterviewLevelById?id=null 404可以明确:请求后端接口时传递的id为null,导致接口无法找到对应数据,最终输入框无法填充内容。

具体代码问题

  1. LocalStorage键名不匹配
    在ViewLevel.js的editLevel方法中,存储id到LocalStorage时用的键是userid:
editLevel(id){
  localStorage.setItem('userid',id);
  window.location=`/updatelevel/${id}`;
}

但在UpdateLevel.js的componentDidMount中,取id时用的键是id:

JobService.GetInterviewLevelById(localStorage.getItem('id'))

键名不一致,导致取出的值为null。

  1. 依赖LocalStorage不可靠
    用LocalStorage传递id存在缓存风险,而且路由地址中已经包含了id(/updatelevel/${id}),直接从路由参数获取更可靠。

修复步骤

步骤1:从路由参数获取id(推荐方案)

直接从路由参数中提取id,无需依赖LocalStorage,避免缓存问题:

修改UpdateLevel.js的componentDidMount方法:

componentDidMount(){
  // 从路由参数获取id,转为数字类型
  const id = parseInt(this.props.match.params.id);
  if(id){
    JobService.GetInterviewLevelById(id).then((res)=>{
      let level=res.data;
      this.setState({
        id: id,
        level: level.level,
        levelDes:level.levelDes
      });
    }).catch(err=>{
      console.error('获取数据失败:', err);
    });
  }
}

简化ViewLevel.js的editLevel方法:

editLevel(id){
  window.location=`/updatelevel/${id}`;
}

步骤2:确保路由配置正确

确认路由配置中UpdateLevel的路由包含参数:

<Route path="/updatelevel/:id" component={UpdateLevel} />

步骤3:优化初始状态(可选)

将UpdateLevel的state中id初始值改为null,更符合实际场景:

this.state={
  id: null,
  level:'',
  levelDes:'',
  errors:{}
}

额外优化建议

  1. 改用React Router导航:避免使用window.location,用history.push进行路由跳转(类组件可通过this.props.history.push):
editLevel(id){
  this.props.history.push(`/updatelevel/${id}`);
}
  1. 添加请求错误处理:在所有axios请求中添加catch块,捕获并处理错误,避免控制台抛出未捕获异常。
  2. 设置id输入框只读:编辑页面的id通常不需要修改,可将输入框设为只读:
<input id="id" name="id" value={this.state.id} onChange={this.id} readOnly />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:06:32