[英]React-Router re-mounts component on route change
I have a connected (to a redux store) component. 我有一个连接(到redux商店)组件。 I have multiple routes that all use this component in a render prop.
我有多个路由都在渲染道具中使用此组件。 On every route change, the entire component appears to be re-mounted.
在每次更改路径时,整个组件似乎都会重新安装。 Is there any way to prevent this from happening?
有没有办法防止这种情况发生? My first thought was that I may be re-instantiating the component every time, due to the render prop being a function that react router calls?
我的第一个想法是,我可能每次都重新实例化组件,因为渲染道具是一个反应路由器调用的函数? Here's some code:
这是一些代码:
const routeFunction =
(resource, props) => <CrudWrapper resource={resource} modelId={props.match.params.id} />
export default crudResources.map(resource => ({
path: `/${resource}/:id?`,
link: `/${resource}`,
resource,
// eslint-disable-next-line react/prop-types
render: routeFunction.bind(null, resource)
}));
The routes are then mapped in JSX: {routes.map(route => <Route key={route.path} {...route} />)}
然后在JSX中映射路由:
{routes.map(route => <Route key={route.path} {...route} />)}
I had the routes wrapped in a <Switch>
and thought this might be causing the issue, but even after removing the switch, the component's componentWillMount
method is called every time. 我将路由包装在
<Switch>
并认为这可能导致问题,但即使在删除开关后,每次都会调用组件的componentWillMount
方法。
The problem appears to be related to the key prop on the route. 问题似乎与路线上的关键支柱有关。 When I omit the key prop, the Component is not remounted.
当我省略关键道具时,组件不会重新安装。 As soon as I add it, no matter what the string is, the route is remounted.
一旦我添加它,无论字符串是什么,路由都会被重新安装。
EDIT: 编辑:
This was my bad. 这是我的坏事。 Since all routes have different keys, react will remount them since they are all different.
由于所有路线都有不同的钥匙,因此反应将重新安排它们,因为它们都是不同的。 See here: https://github.com/ReactTraining/react-router/issues/5972
请参见: https : //github.com/ReactTraining/react-router/issues/5972
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.