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

React Router Dom无法向组件传递状态的问题求助

问题分析与解决方案

核心问题

  1. 函数组件误用this.state:App是函数组件,不存在this对象,直接写this.state.symbol会导致程序崩溃,这是当前崩溃的主要原因。
  2. 状态传递方式错误:试图在Route中给Sell组件传递ticker属性,但该属性值无法通过this.state获取,正确做法是通过Link的state参数传递数据,再在目标组件中读取。

具体修复步骤

1. 修正App.js中的Route配置

移除Route中Sell组件的ticker属性,因为函数组件无法通过this.state获取值,我们将通过路由状态传递数据:

function App() {
  return (
    <div>
      <AuthContextProvider>
        <Navbar/>
        <Routes>
          <Route path='/' element={<Home/>}/>
          <Route path='/showinvestments' element={<Protected><ShowInvestments/></Protected>}/>
          <Route path='/addinvestments' element={<Protected><Add/></Protected>}/>
          {/* 移除错误的ticker属性 */}
          <Route path='/sell/:stockSell' element={<Protected><Sell/></Protected>}/>       
          <Route path='/login' element={<Login/>}/>
        </Routes>
      </AuthContextProvider>
    </div>
  );
}

2. 确保Link的路径与state传递正确

确认sellLink格式正确(比如/sell/${ticker}),同时保持state的键名统一:

<div className='col text-center d-flex ' >
  <Link to={{pathname: sellLink, state: {symbol: ticker}}}>
      <AiFillEdit className='mt-2'/>
  </Link>
</div>

3. 在Sell组件中读取路由状态

使用react-router-dom的useLocation钩子获取传递的state,同时处理state可能为undefined的情况:

import { useLocation } from 'react-router-dom';

const Sell = () => {
  const location = useLocation();
  // 解构state中的symbol,设置默认值避免报错
  const { symbol: ticker = '' } = location.state || {};

  return (
    <div className='container'>
        Hello
        {ticker}
    </div>
  )
}

额外注意事项

  • 确保Sell组件中正确导入了useLocation钩子。
  • 如果用户直接访问/sell/:stockSell路径(非通过Link跳转),location.state会是undefined,设置默认值可避免组件崩溃。
  • 路由参数stockSell和传递的symbol是独立的两个值,若不需要路由参数,可考虑将路径改为/sell,需确保业务逻辑不冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:30:56