在react-router v4中为不同的路由路径使用相同的组件 [英] using same component for different route path in react-router v4

查看:86
本文介绍了在react-router v4中为不同的路由路径使用相同的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用单独的路线,但在我的React应用程序中添加/编辑表单的组件相同,如下所示:

I am trying to have separate routes but same component for add/edit forms in my react app like the below:

<Switch>
        <Route exact path="/dashboard" component={Dashboard}></Route>
        <Route exact path="/clients" component={Clients}></Route>
        <Route exact path="/add-client" component={manageClient}></Route>
        <Route exact path="/edit-client" component={manageClient}></Route>        
        <Route component={ NotFound } />        
</Switch>

现在,在manageClient组件中,我解析查询参数(我在编辑路由中传递带有客户端ID的查询字符串),并根据传递的查询参数有条件地进行渲染.

Now in the manageClient component, I parse the query params (I pass in a query string with client id in edit route), I render conditionally based on the query param passed.

问题在于,这不会再次重新安装整个组件.假设打开了一个编辑页面,并且用户单击添加组件,URL发生了更改,但是该组件没有重新加载,因此保留在编辑页面上.

The problem is that this doesn't remount the whole component again. Say an edit page is opened, and the user clicks on add component, the URL changes, but the component doesn't reload and hence remains on the edit page.

有没有办法解决这个问题?

Is there a way to handle this?

推荐答案

为每个路径使用不同的 key 应该会强制组件进行重建:

Using different key for each route should force components to rebuild:

    <Route 
      key="add-client"
      exact path="/add-client"
      component={manageClient} 
    />

    <Route 
      key="edit-client"
      exact path="/edit-client"
      component={manageClient} 
    />

这篇关于在react-router v4中为不同的路由路径使用相同的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆