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

React数组对象find函数匹配params.id返回undefined问题求助

问题分析与修复方案

核心问题

  • getLawyerId函数未添加return语句,无论find是否找到匹配项,函数都会返回undefined
  • React Router的params.id是字符串类型,后端返回的律师id是数字类型,===严格相等判断会因类型不匹配导致匹配失败
  • 调用getLawyerId时传递了转换后的数字,但函数未定义形参接收该值,参数未被实际使用

修正后的代码

import React from 'react'
import { useParams } from 'react-router-dom'

const Lawyer = ( {lawyersArray} ) => {
  const { id: paramId } = useParams();
  // 将URL参数转为十进制数字
  const targetId = parseInt(paramId, 10);

  // 直接查找匹配的律师
  const lawyerProfile = lawyersArray.find(lawyer => lawyer.id === targetId);

  return (
    <div>
      {lawyerProfile ? (
        <div>
          <h2>{lawyerProfile.first_name} {lawyerProfile.last_name}</h2>
          {/* 可在此添加更多律师资料展示内容 */}
        </div>
      ) : (
        <p>未找到该律师信息</p>
      )}
    </div>
  )
}

export default Lawyer

关键修改说明

  1. 解构useParams时给参数重命名,提升代码可读性
  2. 用parseInt(paramId, 10)将字符串类型的URL参数转为数字,第二个参数10指定十进制,避免进制转换的意外问题
  3. 移除冗余的getLawyerId函数,直接使用find查找(若需保留函数,需确保它有返回值且正确接收参数,示例如下):
function getLawyerId(targetId) {
  return lawyersArray.find(lawyer => lawyer.id === targetId);
}
const lawyerProfile = getLawyerId(targetId);
  1. 添加空值判断,找不到律师时显示提示,避免渲染错误

类型验证小技巧

若不确定参数类型,可在组件中添加打印语句确认:

console.log(typeof paramId); // 输出 "string"
console.log(typeof lawyersArray[0].id); // 输出 "number"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:57:21