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

TypeScript/React设置Well接口files数组category报undefined错误问询

问题根因

  • 报错的直接原因是handleInputChange中获取的well.files[index]为undefined:你在遍历files数组生成表格行时没有把真实的索引值传递给下拉框组件,导致修改时拿到的index和实际数组下标不匹配,访问到了不存在的数组项。
  • 直接修改state引用的写法违反React状态不可变原则,会引发后续渲染异常。
  • 下拉框的value绑定错误:你绑定了全局的this.fileCategory.category而非当前对应文件的category值,会导致所有下拉框显示内容同步错误。

修复代码

1. 修正handleInputChange逻辑,遵循状态不可变原则

private handleInputChange = (index: number) => (event: any) => {
  const newCategory = event.target.value;
  this.setState(prevState => {
    // 逐层拷贝state对象,避免直接修改原状态
    const well = {...prevState.well};
    well.files = [...(well.files || [])];
    well.files[index] = {
      ...well.files[index],
      category: newCategory
    };
    return { well };
  });
}

2. 修正renderDropdown定义和绑定逻辑

// 去掉多余的高阶函数包装,直接接收当前文件的category和对应索引
public renderDropdown = (category: string, index: number) => {
    return (
        <FormGroup >
            <EInput
                type="select"
                name="Category"
                // 绑定当前文件的category值
                value={category}
                onChange={this.handleInputChange(index)}
            >
                <option value="" />
                <option value="Not Categorized">未分类</option>
                <option value="Signed Documents">已签署文件</option>
                <option value="Unsigned Documents">未签署文件</option>
                <option value="3rd Party Documents">第三方文件</option>
                <option value="General Well Info">油井通用信息</option>
            </EInput>
        </FormGroup>
    );
}

3. 修正formatWellFiles中的参数传递

private formatWellFiles = () => {
    // 加兜底逻辑,避免files为undefined时遍历报错
    const files = this.state.well.files || [];
    const headers = [
        "文件名",
        "分类",
        "大小",
        "上传人",
        "上传日期",
        "下载",
    ];
    // map遍历取第二个参数作为当前数组项的真实索引
    const rows = files.map((f, index) => {
        return [
            {
                content: f.name
            },
            {
                // 传入当前文件的category和对应的真实索引
                content: this.renderDropdown(f.category, index),
                sortItem: f.category,
                type: 'render'
            },
            {
                content: this.renderSize(f.size),
                sortItem: Number(f.size),
                type: 'render'
            },
            {
                content: f.createUser
            },
            {
                content: f.createDate
            },
            {
                content: this.renderDownload(f),
                type: 'render',
            },
        ];
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:09:03