【问题标题】:React Router match property null when using custom Route component使用自定义 Route 组件时 React Router 匹配属性 null
【发布时间】:2019-02-26 18:58:07
【问题描述】:

我正在使用ConnectedRouter 组件和自定义路由,如下所示:

const PrivateRoute = ({ layout: Layout, component: Component, rest }) => (

  <Route
    {...rest}
    render={matchProps => (
      <AuthConsumer>
        {({ authenticated }) =>
          authenticated ? (
            <Layout pathname={matchProps.location.pathname}>
              <Component {...matchProps} />
            </Layout>
          ) : (
            <Redirect to={{ pathname: '/login', state: { from: matchProps.location } }} />
          )
        }
      </AuthConsumer>
    )}
  />
)

我是这样使用的:

<Switch>
    <PrivateRoute
      exact
      path={`${match.url}someroute/:id`}
      layout={Layout}
      component={SomePage}
    />
</Switch>

还有一个像这样的组件:

import React from 'react'

const SomePage = ({ match }) => {
  console.log('MATCH ', match.params)
  return <div>TESTING</div>
}

export default SomePage

在这种情况下,match 是空的,它认为它在 '/' 路由上(即使 location 属性说它在 /someroute/123 上。

另一方面,这是可行的:

<Route
      exact
      path={`${match.url}someroute/:id`}
      component={SomePage}
    />

并且匹配会正确更新。

我很困惑为什么会发生这种情况。任何帮助将不胜感激!

【问题讨论】:

    标签: reactjs react-router-v4 react-router-dom


    【解决方案1】:

    啊,我明白了。 rest 应该是 ...rest&lt;Route&gt; 组件没有正确传递 props!

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 2020-03-27
      • 1970-01-01
      • 2020-01-23
      • 2020-09-03
      • 2020-08-20
      • 2021-05-02
      • 2018-12-19
      • 1970-01-01
      相关资源
      最近更新 更多