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

从react-redux store按Id筛选对象时filter返回空数组

问题描述

编写的数组filter方法始终返回空数组,无法获取按Id匹配的目标对象。
控制台输出如下:

operators (51) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]0: created_at: "2022-06-02T07:21:08.492Z"id: 3name: "operator1"phone: 1478subdomain: "test101"updated_at: "2022-06-02T07:21:08.492Z"user_id: 1[[Prototype]]: Object1: {id: 4, name: 'operator4', phone: 14785, subdomain: 'test104', created_at: '2022-06-02T13:13:42.898Z', …}2: {id: 5, name: 'operator12', phone: 14782, subdomain: 'test20', created_at: '2022-06-03T06:51:12.950Z', …}3: {id: 2, name: 'test1r', phone: 1234451699, subdomain: 'sub10', created_at: '2022-06-01T15:51:29.098Z', …}
// 省略中间47条数据
50: {id: 53, name: 'fungy park', phone: 1923571, subdomain: 'sub032', created_at: '2022-07-07T19:53:41.606Z', …}length: 51[[Prototype]]: Array(0)
NewLocation.js:41 

operator []
length: 0[[Prototype]]: Array(0)

原代码实现:

const NewLocations = () => {
  const { operatorId } = useParams();
  console.log('id', operatorId);
  const [successful, setSuccessful] = useState(false);
  const operators = useSelector((state) => state.operators.data)
  console.log('operators', operators);
  const operator = operators.filter((operator) => operator.id === operatorId)
  console.log('operator', operator);
  
  remaining codes... 
}
问题根因

核心问题是类型不匹配:
useParams() 从路由路径中取到的参数默认是字符串类型,但operators数组里存储的id字段是数字类型。代码中用了严格相等符===做判断,要求两边值和类型完全一致才会返回true,类型不同时永远判定为不相等,自然匹配不到任何结果。
额外隐患:Redux中state.operators.data的初始值如果没设置为空数组,首次组件渲染、接口数据还没返回时直接调用filter会直接抛错。

修复方案

把路由取到的operatorId转成数字类型再做匹配,同时加可选链做兼容处理:

const NewLocations = () => {
  const { operatorId } = useParams();
  console.log('id', operatorId);
  const [successful, setSuccessful] = useState(false);
  const operators = useSelector((state) => state.operators.data)
  console.log('operators', operators);
  // 路由参数转数字,兼容初始值空场景
  const targetId = Number(operatorId);
  const operator = operators?.filter((item) => item.id === targetId);
  // 如果id唯一、只需要匹配单个对象,用find性能更好,直接返回对象不需要取数组下标
  // const operator = operators?.find((item) => item.id === targetId);
  console.log('operator', operator);
  
  remaining codes... 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:01:16