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

React项目编译报错:'peoples'未定义(no-undef)求助

解决React中'peoples' is not defined的编译错误

Hey there! Let's break down exactly why you're hitting this 'peoples' is not defined error and how to fix it.

错误根源

The issue is in your state initialization code: when you write filtered: peoples, you're trying to reference a variable named peoples that doesn't exist yet. Even though you declare peoples: [] in the same state object, JavaScript doesn't allow referencing other properties of the same object while it's being initialized. At the line where you set filtered: peoples, the peoples property hasn't been created yet—so JS throws an "undefined" error.

修复方案

Here's how to fix this step by step:

  1. Initialize filtered with a matching default value
    Update your constructor to set filtered to an empty array (matching the initial value of peoples):

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          elementsPerPage: 3,
          currentPage: 0,
          input: "",
          peoples: [],
          filtered: [], // 先初始化为空数组,和peoples默认值保持一致
          // 你的其他state属性...
        };
      }
    }
    
  2. Sync filtered with peoples when fetching API data
    When you retrieve data via Axios, update both peoples and filtered in the same setState call. For example, in your componentDidMount method:

    componentDidMount() {
      axios.get("your-api-endpoint-url")
        .then(response => {
          const fetchedData = response.data;
          this.setState({
            peoples: fetchedData,
            filtered: fetchedData // 将获取到的数据同步给filtered
          });
        })
        .catch(error => console.error("Failed to load data:", error));
    }
    
  3. Update filtered for your search/filter logic
    If you're using the input state to filter the peoples data, use the functional form of setState to safely access the latest peoples state when updating filtered:

    handleInputChange = (e) => {
      const inputValue = e.target.value;
      this.setState(prevState => ({
        input: inputValue,
        filtered: prevState.peoples.filter(person => 
          // 替换成你的具体过滤逻辑,比如匹配姓名
          person.name.toLowerCase().includes(inputValue.toLowerCase())
        )
      }));
    };
    

That's all! This will fix the undefined error and ensure your filtered array stays in sync with your data as expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:17:47