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

React报错:无法读取undefined的state属性及filter不是函数

问题分析与修复

核心错误原因

  1. fetch响应未解析:直接将fetch返回的Response对象赋值给this.state.cars,而非解析后的JSON数组,导致this.state.cars不是数组,无法调用filter方法。
  2. 数据结构不匹配:后端返回的JSON字段是make,但代码中尝试访问i.label,而react-select的选项要求必须包含label和value属性。

修复步骤

1. 正确解析响应并转换数据结构

在componentDidMount中先解析JSON响应,再将数据转换成react-select需要的格式:

componentDidMount() {
  fetch(url)
    .then(res => res.json()) // 解析JSON响应
    .then(data => {
      // 转换为react-select要求的label/value结构
      const carsOptions = data.map(car => ({
        label: car.make,
        value: car.make, // 用make作为唯一标识,也可自定义
        link: car.link // 保留原字段供后续使用
      }));
      this.setState({ cars: carsOptions });
    })
    .catch(err => console.error('数据请求失败:', err)); // 增加错误捕获
}

2. 优化函数定义(可选)

将filterCars和loadOptions移出render,避免每次渲染重复创建函数:

filterCars = (inputValue) => {
  return this.state.cars.filter((i) =>
    i.label.toLowerCase().includes(inputValue.toLowerCase())
  );
};

loadOptions = (inputValue, callback) => {
  setTimeout(() => {
    callback(this.filterCars(inputValue));
  }, 1000);
};

完整修正代码

import React, { Component } from 'react';
import AsyncSelect from 'react-select/async';

export default class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: null,
      cars: []
    };
  }

  componentDidMount() {
    fetch(url)
      .then(res => res.json())
      .then(data => {
        const carsOptions = data.map(car => ({
          label: car.make,
          value: car.make,
          link: car.link
        }));
        this.setState({ cars: carsOptions });
      })
      .catch(err => console.error('数据请求失败:', err));
  }

  handleInputChange = (newValue) => {
    const inputValue = newValue.replace(/\W/g, '');
    this.setState({ inputValue });
    return inputValue;
  };

  filterCars = (inputValue) => {
    return this.state.cars.filter((i) =>
      i.label.toLowerCase().includes(inputValue.toLowerCase())
    );
  };

  loadOptions = (inputValue, callback) => {
    setTimeout(() => {
      callback(this.filterCars(inputValue));
    }, 1000);
  };

  render() {
    return (
      <div>
        <AsyncSelect
          cacheOptions
          loadOptions={this.loadOptions}
          defaultOptions
          onInputChange={this.handleInputChange}
        />
      </div>
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 01:36:24