React项目编译报错:'peoples'未定义(no-undef)求助
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:
Initialize
filteredwith a matching default value
Update your constructor to setfilteredto an empty array (matching the initial value ofpeoples):class App extends Component { constructor(props) { super(props); this.state = { elementsPerPage: 3, currentPage: 0, input: "", peoples: [], filtered: [], // 先初始化为空数组,和peoples默认值保持一致 // 你的其他state属性... }; } }Sync
filteredwithpeopleswhen fetching API data
When you retrieve data via Axios, update bothpeoplesandfilteredin the samesetStatecall. For example, in yourcomponentDidMountmethod: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)); }Update
filteredfor your search/filter logic
If you're using theinputstate to filter thepeoplesdata, use the functional form ofsetStateto safely access the latestpeoplesstate when updatingfiltered: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

