使用React Hooks删除API数据项时提示filter不是函数的问题求解
报错原因
- 子组件接收的
weather是单条对象类型:你在父组件中遍历天气列表渲染DataProfile时,给每个子组件传递的是数组的单个元素(对象类型),而filter是数组专属方法,对象调用该方法自然会抛出filter is not a function错误。 - 删除逻辑位置错误:修改全量天气数组的逻辑属于父组件的状态操作范畴,不应该放在仅渲染单条数据的子组件内实现,子组件本身无法拿到完整的天气数组。
- 事件绑定存在疏漏:代码中按钮点击事件绑定
removeCity时没有传递要删除的条目id,同时未定义maxTemp变量直接渲染,也会引发额外的运行报错。
修复方案
步骤1:调整子组件逻辑
子组件仅承担单条数据渲染和删除动作触发的能力,不操作全局状态,代码调整如下:
function DataProfile({ weather, onRemove }) { const { id } = weather; const cityName = weather.city.name; const countryName = weather.city.country; const minTemp = weather.list[0].main.temp_min; // 补全缺失的maxTemp定义 const maxTemp = weather.list[0].main.temp_max; return ( <div> <div className="list"> <button onClick={() => onRemove(id)} > x </button> <p> {cityName} {countryName} </p> <p>MaxTemp : {maxTemp}</p> <p>MinTemp : {minTemp}</p> </div> </div> ); }
步骤2:父组件实现删除逻辑
在持有全量weather状态的父组件中编写删除方法,遍历数组时给子组件传递对应参数:
// 父组件内代码示例 import { useState } from 'react'; import DataProfile from './DataProfile'; function ParentComponent() { // 你已经初始化的数组状态 const [weather, setWeather] = useState([]); // 全量数组的删除逻辑 const handleRemoveCity = (itemId) => { // 使用函数式更新确保拿到最新的状态值,规避闭包陷阱 setWeather(prevWeather => prevWeather.filter(({ id }) => id !== itemId)); }; return ( <div className="weather-list"> {/* 遍历全量数组渲染子组件 */} {weather.map(item => ( <DataProfile key={item.id} weather={item} onRemove={handleRemoveCity} /> ))} </div> ); }
内容的提问来源于stack exchange,提问作者Sam RQ
相关产品推荐
相关产品推荐

