简体   繁体   English

为什么在使用反应路由器 v6 链接传递道具时 location.state 为空?

[英]Why location.state is null when using react router v6 link to pass props?

Here is my section.js code, I used state to pass props这是我的 section.js 代码,我使用 state 来传递 props

<Link to="/tesla-clone/order" state={{ model: "model s" }}>
  <LeftButton>
    {leftText}
  </LeftButton>
</Link>

Here is my order.js, I used location to catch the props这是我的 order.js,我使用位置来捕捉道具

function Order() {
    const location = useLocation()
    const {model} = location.state
....
<OrderRight>
  <h1>{model}</h1>
  <p>Estimated Delivery: Nov 2022 - Feb 2023</p>
  <Options>
    <p>Purchase Price</p>
    <p>Potential savings</p>
  </Options>
....

In the app.js, I defined route here在 app.js 中,我在这里定义了路由

<div>
  <Routes>
    <Route path="tesla-clone" element={<Homepage />} />
    <Route path="tesla-clone/order" element={<Order />} />
  </Routes>
</div>

I got an error: Uncaught TypeError: Cannot destructure property 'model' of 'location.state' as it is null.我收到一个错误:未捕获的类型错误:无法解构“location.state”的属性“模型”,因为它为空。 Can somebody help me with this problem?有人可以帮我解决这个问题吗? Thanks a lot!非常感谢! image of the error错误的图像

I found the solution!我找到了解决方案! I should write我应该写

const { state } = useLocation()
const { model } = state

It works pretty well.它工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM