简体   繁体   中英

React router Link with 'to' prop as object is not rendering correct component

I have simple app with react-router v5. In App component I have switch like this:

<Switch>
  <Route path="/post">
    <Post />
  </Route>
  <Route path="*">
    <Error />
  </Route>
</Switch>

In other component I have Link with path like this:

<Link to={{ pathname: `/post?id=${message.id}`, state: { message } }}>text</Link>

Now, Error component is only logging the pathname and state from useLocation() hook, Post component is showing pathname in HTML tag.

When I click the link, the component that is rendered, is 'Error', it console.log correct path name ('.post?id=123'), and it logs correct state. Address in browser is correct, but Post component is not rendered. When I refresh browser, then correct component is rendered. I mean when i refresh being on post?id=123, then 'Post' is rendered, but when I try to click link directing to 'post?id=123', 'Error' is rendered. If I use <Link to={ /post?id=${message.id} /> without state, routing is working fine.

Here's codesanbox , it seems the issue is this part: to={{pathname: '/post?id=${message.id}, state: {message}}, when I remove?id=${...} it works fine. But still I would like to have this id there.

It seems I shouldn't use query string when using object as 'to' parameter. If someone needs to include query string, there is search parameter in 'to' object.

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