【问题标题】:React Router with array of paths + exact still initializes components when location does not match当位置不匹配时,具有路径数组 + 精确的 React Router 仍会初始化组件
【发布时间】:2020-05-20 16:34:25
【问题描述】:

我正在使用 ReactRouter v5。我们有一个设置,其中有 2 条可能的路线来呈现 Component1,而有一条路线来呈现 Component2。但是,在我的测试中,它意外地初始化了组件 1。

const UsersRoutes: FC = () => {
  const location = useLocation();
  console.log(location)
  return (
    <Switch>
      <Route exact path={[routes.admin.users.root, routes.admin.users.import]} >
                {console.log('hi there i should not log') // I would not expect this to be called}
        <Users />
      </Route>
      <Route path={routes.admin.users.user.root()}>
        <UserRoutes />
      </Route>
    </Switch>
  );
};

在我的测试中:

describe('<User />', () => {
  test('user root redirects to profile', async () => {
    const { findByText, history, findByLabelText } = renderWithRouter(
      <UsersRoutes />,
      {
        route: routes.admin.users.user.root(testId),
      }
    );

    expect(history.location.pathname).toEqual(`/admin/users/${testId}/profile`);
    await findByText('profile');
    await findByLabelText('profile');
  });
});

控制台输出:

console.log src/screens/App/screens/Admin/screens/Users/routes.tsx:9
    actual location hook:  {
      pathname: '/admin/users/123-test',
      search: '',
      hash: '',
      state: undefined,
      key: 'kdljhy'
    }

  console.log src/screens/App/screens/Admin/screens/Users/routes.tsx:14
    hi there i should not log

  console.log src/screens/App/screens/Admin/screens/Users/routes.tsx:9
    actual location hook:  {
      pathname: '/admin/users/123-test/profile',
      search: '',
      hash: '',
      state: undefined,
      key: 'zdaam2'
    }

  console.log src/screens/App/screens/Admin/screens/Users/routes.tsx:14
    hi there i should not log

那么,exact 属性在使用路径匹配数组时如何工作?这真的是预期的吗? location 的日志中没有任何内容表明该路径应该已匹配。

【问题讨论】:

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


    【解决方案1】:

    根据 React ReactTraining,这是预期的行为:

    https://github.com/ReactTraining/react-router/issues/7726#issuecomment-750755953

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-01
      • 2021-07-06
      • 2018-05-09
      • 2017-02-11
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多