React Redux向子组件传props时报cannot read property 'filter' of undefined
报错根因
你调用filter数组方法的目标变量为undefined,导致方法调用失败,触发该报错。
修复步骤
1. 统一Reducer结构的访问规则
你编写的Dishes Reducer返回的是嵌套结构:
{ isLoading: Boolean, errMess: String, dishes: Array // 实际存储数组的字段嵌套在对象下 }
你访问菜品数组时用的this.props.dishes.dishes是符合结构的,但访问评论、促销、领导人数据时,直接对上层对象调用了filter方法。如果这三个Reducer的结构和Dishes一致(都是嵌套了同名数组的对象),需要补全访问层级:
- 促销数组访问方式改为:
this.props.promotions.promotions - 评论数组访问方式改为:
this.props.comments.comments - 领导人数组访问方式改为:
this.props.leaders.leaders
2. 添加加载状态判断与空值保护
你在componentDidMount生命周期才触发异步数据拉取,首次渲染时请求还未返回,需要先判断加载状态、错误状态再渲染业务组件,同时用可选链、默认值避免空值调用方法:
修改后的HomePage代码:
const HomePage = () => { // 先判断加载状态 if (this.props.dishes.isLoading || this.props.promotions.isLoading || this.props.leaders.isLoading) { return <div>数据加载中</div> } // 再判断错误状态 if (this.props.dishes.errMess || this.props.promotions.errMess || this.props.leaders.errMess) { return <div>加载失败:{this.props.dishes.errMess || this.props.promotions.errMess || this.props.leaders.errMess}</div> } return( <Home dish={this.props.dishes.dishes?.filter((dish) => dish.featured)[0] ?? null} dishesLoading={this.props.dishes.isLoading} dishesErrMess={this.props.dishes.errMess} promotion={this.props.promotions.promotions?.filter((promo) => promo.featured)[0] ?? null} leader={this.props.leaders.leaders?.filter((leader) => leader.featured)[0] ?? null} /> ); }
修改后的DishWithId代码:
const DishWithId = ({match}) => { if (this.props.dishes.isLoading || this.props.comments.isLoading) { return <div>数据加载中</div> } if (this.props.dishes.errMess || this.props.comments.errMess) { return <div>加载失败:{this.props.dishes.errMess || this.props.comments.errMess}</div> } return( <DishDetail dish={this.props.dishes.dishes?.filter((dish) => dish.id === parseInt(match.params.dishId,10))[0] ?? null} isLoading={this.props.dishes.isLoading} errMess={this.props.dishes.errMess} comments={this.props.comments.comments?.filter((comment) => comment.dishId === parseInt(match.params.dishId,10)) ?? []} addComment={this.props.addComment} /> ); };
3. 确认根Reducer正确注册
检查你调用combineReducers的根Reducer文件,确认所有Reducer都已正确挂载到对应state字段下,未注册的state字段默认值为undefined,也会触发该报错。参考根Reducer写法:
import { combineReducers } from 'redux'; import { Dishes } from './dishes'; import { Comments } from './comments'; import { Promotions } from './promotions'; import { Leaders } from './leaders'; export default combineReducers({ dishes: Dishes, comments: Comments, promotions: Promotions, leaders: Leaders });
内容的提问来源于stack exchange,提问作者Blake Dong
相关产品推荐
相关产品推荐

