React类组件如何在componentDidMount中对服务端JSON数据做filter筛选
React类组件filter筛选问题修复方案
核心问题排查
- 作用域错误:
shopid仅在render方法内定义,componentDidMount中无法访问该变量,筛选条件直接失效,这是筛选结果为空的核心原因之一。 - filter回调无返回值:你使用花括号包裹filter的回调逻辑但未显式写
return,回调默认返回undefined,所有元素都会被过滤,最终得到空数组。正确写法要么去掉花括号隐式返回,要么在判断前加return。 - state赋值错误:筛选后的结果存在临时变量
item中,但调用this.setState时依然传入了未筛选的原始data,state根本没有保存筛选结果。 - 变量未声明:
item、shopid、itemArray均未使用let/const声明,会抛出变量未定义的报错,你遇到的"filter不支持"的提示大概率是该类报错的误判。 - 无效打印:代码中打印的
itemArray从未被定义,必然抛出异常。
修复后代码
// 首先在constructor中初始化state,避免首次渲染报错 constructor(props) { super(props); this.state = { item: null } } componentDidMount() { // 直接在componentDidMount中获取shopid,不用等render执行 const navItem = this.props.navigation.getParam('item'); const shopid = navItem.shop_id; fetch("http://0.0.0.0:8001/shopData") .then(response => response.json()) .then(data => { // 修复filter回调写法,隐式返回判断结果 const filteredItem = data.filter(item => item.id === shopid); // 把筛选后的结果存入state this.setState({ item: filteredItem }); console.log(filteredItem); }) .catch(err => { console.log("Error loading data" + err); }); } render(){ // 从state取筛选后的数据,navigation参数仅用于 fallback 或其他逻辑 const navItem = this.props.navigation.getParam('item'); const shopid = navItem.shop_id; const { item } = this.state; return( <View> <Text>The title </Text> <Text>{shopid}</Text> <Text>{navItem.name} </Text> {/* 渲染筛选后的数据,加判断避免state未初始化时报错 */} {item && <Text>筛选后店铺ID:{item[0]?.id}</Text>} </View> ) }
额外注意点
如果筛选结果依然为空,可检查item.id和shopid的类型是否一致,例如一个是数字类型一个是字符串类型时,===全等判断会返回false,可转成同类型后再比较:item.id.toString() === shopid.toString()。
内容的提问来源于stack exchange,提问作者Walking Man
相关产品推荐
相关产品推荐

