reactjs - React Router 开关不会为不同的路由安装相同的组件

标签 reactjs react-router

我定义了这些路由

<Switch>
    <Route path='/1' render={() => <ComponentA />} /> 
    <Route path='/2' render={() => <ComponentA />} />
    <Route path='/3' render={() => <ComponentA />} />
</Switch>

当我点击/1 页面上的应用程序时,ComponentA 呈现良好。 但是当我导航到/2 时,ComponentA 不会被重新挂载,但渲染函数会触发。

如果我使用不同的组件,它会被正确安装

ComponentA 根据 props 更改要渲染的内容,并在 componentDidMount 中触发检索数据的操作

这是预期的行为吗,看起来我们不应该为不同的路由重用组件

最佳答案

只需在您的渲染组件上添加一个唯一键 - 这已为我修复。

<Switch>
   <Route path='/1' render={() => <ComponentA key={1} />} /> 
   <Route path='/2' render={() => <ComponentA key={2} />} />
   <Route path='/3' render={() => <ComponentA key={3} />} />
</Switch>

关于reactjs - React Router 开关不会为不同的路由安装相同的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49567416/

相关文章:

reactjs - React 组件目录的命名约定

javascript - React.js : How to render separated jsx modules from one app. jsx 文件?

javascript - React JS 中的 registerServiceWorker 做了什么?

javascript - 使用 React router 进行 enzyme 集成测试测试 - 使用链接测试组件更新

javascript - TS错误: Type 'unknown' is not assignable to type 'FunctionComponent<any> due to withRouter

reactjs - Material UI withStyles : Invalid prop `component` of type `object` supplied to `Route` , 预期 `function`

javascript - React - 使用 for 循环创建 x 个组件实例

javascript - 如何在 react 组件中加载脚本

javascript - 使用 react 路由器选择新项目时刷新组件

reactjs - React Route 组件上出现类型错误