在react-router v4中使用相同的组件用于不同的路由路径

beN*_*erd 28 javascript reactjs react-router-v4

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

有办法处理这个吗?

小智 44

使用不同的键应该强制组件重建:

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

    <Route 
      key="edit-client"
      exact path="/edit-client"
      component={manageClient} 
    />
Run Code Online (Sandbox Code Playgroud)


Vig*_*ran 10

<Route exact path={["/add-client", "/edit-client"]}>
  <manageClient />
</Route>
Run Code Online (Sandbox Code Playgroud)

参考

版本5.2.0

https://reacttraining.com/react-router/web/api/Route/path-string-string


May*_*kla 6

一种解决方案是对组件使用内联函数,每次都会渲染一个新组件,但这不是一个好主意。

像这样:

<Route exact path="/add-client" component={props => <ManageClient {...props} />}></Route>
<Route exact path="/edit-client" component={props => <ManageClient {...props} />}></Route> 
Run Code Online (Sandbox Code Playgroud)

更好的解决方案是在component中使用componentWillReceiveProps生命周期方法ManageClient。想法是,当我们为两条路径渲染相同的组件并在它们之间切换时,react将不会进行unmount-mount组件,它基本上只会更新该组件。因此,如果您进行任何api调用或需要一些数据,请在更改路线时使用此方法全部完成。

要进行检查,请使用此代码,然后查看其是否会在路线更改时被调用。

componentWillReceiveProps(nextProps){
   console.log('route chnaged')
}
Run Code Online (Sandbox Code Playgroud)

注意:仅当路线更改时,设置条件并进行api调用。

  • 从React 16.3开始不推荐使用componentWillReceiveProps (3认同)