简体   繁体   中英

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

<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

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

<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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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