我对react-router-dom
(v4.3.1)中Route
的使用有两个疑问:
-
我们什么时候在
Route
中使用component
与render
:<Route exact path='/u/:username/' component={ProfileComponent} /> <Route exact path='/u/:username/' render={() => <ProfileComponent />} />
- 如何以两种方式访问URL中的变量
username
?
当您将组件传递给component
prop 时,该组件将获取props.match.params
对象中的路径参数,即在您的示例中props.match.params.username
:
class ProfileComponent extends React.Component {
render() {
return <div>{this.props.match.params.username}</div>;
}
}
使用render
prop 时,可以通过提供给render
函数的 props 访问路径参数:
<Route
exact
path='/u/:username/'
render={(props) =>
<ProfileComponent username={props.match.params.username}/>
}
/>
当您需要包含路由的组件中的一些数据时,您通常会使用render
prop,因为component
prop 没有提供将其他 props 传递给组件的真正方法。