简体   繁体   English

React router Link with 'to' prop as object 没有渲染正确的组件

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

I have simple app with react-router v5.我有 react-router v5 的简单应用程序。 In App component I have switch like this:在 App 组件中,我有这样的开关:

<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.现在,错误组件仅从 useLocation() 挂钩记录路径名和 state,Post 组件在 HTML 标记中显示路径名。

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.当我单击该链接时,呈现的组件是“错误”,它 console.log 正确的路径名(“.post?id=123”),并且它记录了正确的 state。 Address in browser is correct, but Post component is not rendered.浏览器中的地址正确,但 Post 组件未呈现。 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.我的意思是当我在 post?id=123 上刷新时,会呈现“Post”,但是当我尝试单击指向“post?id=123”的链接时,会呈现“Error”。 If I use <Link to={ /post?id=${message.id} /> without state, routing is working fine.如果我在没有 state 的情况下使用 <Link to={ /post?id=${message.id} />,则路由工作正常。

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.这是codesanbox ,似乎问题出在这部分:to={{pathname: '/post?id=${message.id}, state: {message}},当我删除它时?id=${...}工作正常。 But still I would like to have this id there.但我仍然希望有这个 id。

It seems I shouldn't use query string when using object as 'to' parameter.使用 object 作为 'to' 参数时,似乎我不应该使用查询字符串。 If someone needs to include query string, there is search parameter in 'to' object.如果有人需要包含查询字符串,'to' object 中有搜索参数。

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

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