get useLocation props from Route : Uncaught TypeError: Cannot read properties of null (reading 'isNew')

get useLocation props from Route : Uncaught TypeError: Cannot read properties of null (reading 'isNew')

我是 reactjs 的新手,我想访问我的组件 Bdc,当我单击另一个组件中的按钮时,首先使用两种方式,当我直接使用其路径访问组件时,另一种方式在搜索栏中。

第一种方法是使用 useLocation

<Button 
   variant="contained" 
   onClick={() => navigate("/nouveauBdc", {state: {id: '', isNew: true}})}>
         NOUVEAU BON DE COMMANDE
 </Button>

在我的组件中,我可以读取从 navigate("/nouveauBdc", {state: {id: '', isNew: true}})

发送的状态

但是当我将我的组件的路径放在搜索栏中时的第二种方式 http://localhost:3001/nouveauBdc 我得到了这个错误

Uncaught TypeError: Cannot read properties of null (reading 'isNew')

Bdc 组件:这是我收到错误的行:

React.useEffect(() => {
    setBdcState(location.state as BdcProps);
  }, [location])

React.useEffect(() => {
    if(!bdcState.isNew){
      //get data
    }
  }, [bdcState.isNew]) // the line error

我的路线 我把 Link 从这里传递状态但是不工作

<BrowserRouter>
    <Routes>
      <Route path="/nouveauBdc" element={<ProtectedRoutes/>}>
         <Route path="/nouveauBdc" element={<Bdc />} />
      </Route>
          
      <Route path="*" element={<h1>404 - Page non trouvée</h1>} />
      <Route path="/accessDenied" element={<h1>403 - Accès interdit</h1>} />
    </Routes>
    <Link to={'nouveauBdc'} state={{ state: {id: '', isNew: true} }} >Page 1</Link>

  </BrowserRouter>,

ProtectedRoutes.tsx

const user = () => {
    if(userAuth)){
      return(
        <Outlet/>
      );
    } else {       
      return(
        <Navigate to="/accessDenied"/>
      );          
    } 
  }
  
  return(
    <div>
      {user()}
    </div>
    );

请问在直接访问组件(搜索栏)时是否也发送状态的解决方案

你不能直接从地址栏设置状态,它总是为空(当然,空没有任何属性,所以你会得到错误)。

如果要在 URL 栏中插入位置时显示组件,则应改用 location.search。这将向您的 url 添加一个查询,例如 ?bcdState=new,您可以在加载类似于 location.state.

的组件时阅读它