【发布时间】: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