对于Route( v4.3.1 )中react-router-dom的使用,我有两个疑问:

  • 我们何时在component中使用renderRoute:
    <Route exact path='/u/:username/' component={ProfileComponent} />
    <Route exact path='/u/:username/' render={() => <ProfileComponent />} />
    
  • 如何通过两种方式访问​​ URL 中的变量username
  • 最佳答案

    当您将组件传递给component属性时,该组件将在props.match.params对象中获取路径参数,即您的示例中的props.match.params.username:

    class ProfileComponent extends React.Component {
      render() {
        return <div>{this.props.match.params.username}</div>;
      }
    }
    

    当使用render属性时,可以通过给render函数提供的属性来访问路径参数:
    <Route
      exact
      path='/u/:username/'
      render={(props) =>
        <ProfileComponent username={props.match.params.username}/>
      }
    />
    

    当您需要包含包含路线的组件中的一些数据时,通常会使用render Prop ,因为component Prop 并没有提供将其他 Prop 传递给组件的真正方法。

    09-25 17:44
    查看更多