React Router V4用<link />替换参数

时间:2018-08-10 09:22:58

标签: reactjs react-router

我的DashBoard组件呈现了一个名为PostComments的共享组件,该共享组件呈现了一个用<Link/>包装的列表,单击列表后,页面导航到Profile组件,在此组件我也有PostCOmments

现在,如果我单击Profile组件上的列表之一,则url参数将像这样堆积,http://localhost:8080/#/dashboard/5b6c5223514959110c492086/49182d98319138e31da42356

<Link replace to={`${match.url}/${i.comment_from._id}`}>
     <div className="comment-user-image" style={{backgroundImage: `url(${i.comment_from.photo_url})`}}>
     </div>
</Link>

1 个答案:

答案 0 :(得分:0)

您需要手动替换网址的最后一部分,因为您会重复使用它。

const splitUrl = match.url.split('/'); // Split into array
splitUrl.splice(-1, 1, i.comment_from_id); // Replace the last part with the new id
return ( 
  <Link replace to={splitUrl.join('/')}> // Recreate the correct url
  // ...