You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router使用箭头函数传参时组件重渲染问题咨询

解决React路由传递Props时Home组件重复挂载的问题

Hey there! Let's break down why your Home component keeps re-mounting (and triggering componentDidMount) when navigating to nested routes, then fix it up step by step.

问题根源

When you use component={() => <Home changeAuth={this.changeAuth} auth={auth} />}, you're passing an anonymous arrow function to the Route's component prop. Every time the router re-renders (like when you jump to /home/info), it creates a brand new instance of this arrow function. React sees this as a completely new component type, so it unmounts the old Home component and mounts a fresh one—this is why componentDidMount runs every time.

On the flip side, using component={Home} passes the actual component reference directly. React can reuse the same component instance across route changes, so no unnecessary unmount/mount cycle occurs.

解决方案

1. 使用render属性替代component属性

This is the recommended approach from React Router for passing props to route components. The render prop lets you return your component via a function, but React will reuse the component instance instead of creating a new one each time. You can also pass through the router's built-in props (like match, location, history) if you need them:

<Route 
  path="/home" 
  render={(routeProps) => (
    <Home 
      {...routeProps} 
      changeAuth={this.changeAuth} 
      auth={auth} 
    />
  )} 
/>

2. 用React.memo包装Home组件(针对函数组件)

If your Home component is a functional component, wrapping it with React.memo will make it skip re-renders when props haven't changed. Pair this with the render prop above for optimal performance:

const Home = React.memo(({ changeAuth, auth, ...routeProps }) => {
  // Your Home component logic here
});

3. 使用Route的children属性传递组件

Another option is to render Home as the child of the Route. This way, Home stays mounted even when navigating to nested routes, and you can pass props directly:

<Route path="/home">
  <Home changeAuth={this.changeAuth} auth={auth} />
</Route>

Note: With this approach, Home will render even if the /home path isn't an exact match. If you want to only show Home when /home is matched, use useRouteMatch (in functional components) or check the match prop (in class components) to conditionally render content.

最终建议

The render prop method is the most straightforward and aligned with React Router's best practices—it solves the re-mounting issue while letting you pass all the props you need.

内容的提问来源于stack exchange,提问作者Trần Mạnh Cường

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:40:01