reactjs 当位置不匹配时,具有路径数组+精确的React Router仍然初始化组件

wn9m85ua  于 2023-05-28  发布在  React
关注(0)|答案(1)|浏览(114)

使用React Router v5。我们有一个设置,其中有两个可能的路由来渲染Component1,一个路由来渲染Component2。然而,在我的测试中,它意外地初始化了Component1

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的日志中没有任何内容表明应该匹配此路径。

q1qsirdb

q1qsirdb1#

根据React ReactTraining,这是预期的行为:
https://github.com/ReactTraining/react-router/issues/7726#issuecomment-750755953

相关问题