React-Router在路线更改时重新安装组件 [英] React-Router re-mounts component on route change
问题描述
我有一个已连接(到redux存储)的组件.我有多个路由,所有路由都在渲染道具中使用此组件.每次更改路线时,似乎都需要重新安装整个组件.有什么办法可以防止这种情况的发生?我的第一个想法是,由于render prop是对路由器调用做出反应的函数,因此我可能每次都重新实例化该组件吗?这是一些代码:
I have a connected (to a redux store) component. 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)
}));
然后在JSX中映射路由:{routes.map(route =>< Route key = {route.path} {... route}/>)}
The routes are then mapped in JSX:
{routes.map(route => <Route key={route.path} {...route} />)}
我将路由包裹在< Switch>
中,并认为这可能是导致问题的原因,但是即使删除了交换机,该组件的 componentWillMount
方法也被称为每次.
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.
推荐答案
问题似乎与路线上的关键道具有关.省略关键道具时,不会重新安装组件.一旦添加,无论字符串是什么,都会重新安装路由.
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.
这是我的坏事.由于所有路由都具有不同的密钥,由于它们均不同,因此react将重新安装它们.参见此处: https://github.com/ReactTraining/react-router/issues/5972
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
这篇关于React-Router在路线更改时重新安装组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!