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

React路由传递Props时获取到undefined的问题排查

问题分析与解决方案

问题根源

  • React Router的<Route>组件不支持直接传递自定义props(比如你写的loading、contacts),这些属性不会被转发到对应的element组件中。你当前的写法里,loading和contacts只是给<Route>本身添加了属性,但<Contacts>组件根本接收不到。
  • 另外你的useState命名存在语义混淆:const [getContacts , setContacts] = useState([]);里的状态变量应该叫contacts而非getContacts,getContacts听起来像获取数据的方法,不符合状态变量的命名逻辑。

修复后的代码

App组件修改:

将loading和修正命名后的contacts直接传递给<Contacts>组件,放在element的JSX标签内:

const App = () => {
  
  // 修正状态变量命名,符合语义规范
  const [contacts , setContacts] = useState([]);
  const [loading , setLoading] = useState(false);
  
  return(
    <div className='App'>
        <Navbar/>
       
        <Routes>
          <Route path='/' element = {<Navigate to="/contacts"/>}/>

          {/* 正确传递props给Contacts组件 */}
          <Route path='/contacts' element={<Contacts contacts={contacts} loading={loading} />} />

          <Route path="/contacts/add" element = {<AddContact/>}/>

          <Route path = "/contacts/:contactId" element = {<ViewContact/>}/>

          <Route path = "/contacts/edit/:contactId" element = {<EditContact/>}/>

          <Route path="*" element={
              <div className='text-light py-5'>
                Not Found!
              </div>
          } />

        </Routes>

    </div>
);
export default App;

Contacts组件保持不变:

const Contacts = ({ contacts, loading }) => {
    return (
        <>
            <div>{contacts}</div>
            <div>{loading}</div>
        </>
    );
};

export default Contacts;

补充说明

  • React Router v6的<Route>组件只接受官方定义的属性(如path、element、index等),自定义属性不会被处理。所有需要传递给页面组件的props,都必须通过element中的JSX直接传递。
  • 状态变量命名尽量遵循[变量名, set变量名]的规范,避免和函数名混淆,提升代码可读性。

内容的提问来源于stack exchange,提问作者Javad-M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 12:59:30