React Router4的component和render的基本使用

558 阅读1分钟
  • 通过component指定的组件会接受默认参数{ match, history, location }
<Route path="/public" component={PublicPage}/>
       
function PublicPage({location, match, history}) {
   console.log(location)
   console.log(match)
   console.log(history)
   return <h3>Public</h3>;
}
  • 通过render传递一个函数,在函数中返回指定组件。这种情况下,从render函数的props包含{ match, history, location }。
<Route
  exact
  path='/u/:username/'
  render={(props) => 
    <ProfileComponent username={props.match.params.username}/>
  }
/>
const ProfileComponent = ({ username }) => {  return <div>{username}</div>;
}
  • 如果要为返回的组件传递额外数据(除了{ match, history, location }),使用render函数

const RouteWithSubRoutes = (route) => (
  <Route path={route.path} render={(props) => (
    <route.component {...props} routes={route.routes}/> //把额外数据routes传递给返回的组件
  )}/>
)
  • 当使用component的时候,router会用React.createElement 创建子组件。这意味着如果给component属性传入一个内联函数,会导致每次render都创建一个新的组件——原来的子组件被卸载,而不是被更新。如果要使用内联函数渲染组件,使用render或者children