无法迁移到react-router v4

时间:2018-01-15 18:04:39

标签: react-router react-router-v4

我无法迁移到使用嵌套路由对路由器4做出反应。以下是我之前代码中的一些片段。是我的布局容器,如果登录,则所有内容都会在其中呈现(否则重定向到登录)

ReactDOM.render(
<Provider store={ store }>
<div>
  <Router history={ history }>
    <Route path='/login' component={ Login } />
    <Route path="/password/reset" component={PasswordReset} />
    <Route path='/register' component={ Register } title={ 'Register' } />
    <Route path='/password/change/:token' component={ ChangePassword } title={ 'Register' } />
    <Route component={ EnsureLoggedInContainer }>
      <Redirect from='/' to='/dashboard' />
      <Route path='/' component={ App }>
        <Route path='/logout' component={ Logout } />
  ....
  </Router>
</div>

来渲染子组件:

class ContentLayout extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
  let children = null;
  if (this.props.children) {
    children = React.cloneElement(this.props.children, {
      updateHeader: this.props.updateHeader,
    });
  }
  return (
    <div className={ this.props.cls }>
      <MainHeader
        updateHeader={ this.props.updateHeader }
        header={ this.props.header }
      />
      {children}
    </div>
  );
}
}

使用v4,我一直试图找出正确的渲染方式,以及其中的任何子组件。到目前为止,我一直试图让它工作,但觉得我走错了路。 (目前props.match总是指向&#39; /&#39;)

ReactDOM.render(
<Provider store={ store }>
  <ConnectedRouter history={history}>
    <div>
        <Switch>
          <Route exact path='/login' component={ Login } />
          <Route exact path="/password/reset" component={PasswordReset} />
          <Route exact path='/register' component={ Register } />
          <Route exact path='/password/change/:token' component={ ChangePassword } />
          <Route path='/' component={ App } />
        </Switch>
      </div>
  </ConnectedRouter>
</Provider>,
document.getElementById('app')
);

在App

const RouteWithProps = ({ component: Component, props, ...extraProps})=> {
 return (<Route
  {...extraProps} 
  render={() => <Component {...props} {...extraProps} />} 
  />
 );
}

并使用组件渲染

{securedRoutes.map((route, i) => (
    <RouteWithProps key={i} {...route} updateHeader={this.props.updateHeader} location={this.props.location} match={this.props.match} />
))}

什么是正确的方法或如何构建应用程序的一个很好的例子,以便布局的所有登录路线

<App>
  <ContentLayout>
    <Child>

使用app将updateHeader等道具传递给所有孩子。

1 个答案:

答案 0 :(得分:0)

我通过删除传递位置和匹配到RouteWithProps来实现它。 在处理类似于/.../:id和/.../的事物的嵌套路由时,我遇到了RouteWithSubRoutes示例的问题:最终这样做是为了使工作能够继续工作。不要认为这是理想的,但会在最佳实践的另一个答案之前起作用。

const RouteWithProps = ({ component: Component, ...extraProps }) => {
  return (<Route exact path={extraProps.path}
    {...extraProps} 
    render={matchProps => <Component {...matchProps} {...extraProps} 
    />} 
   />
  );
}

还删除了传递this.props.location并匹配此组件。

相关问题