页面加载时选择的 NavLink activeClassName

NavLink activeClassName selected on page load

是否可以在 useEffect 上使用 history.push 推送路由的 url 以在页面加载时保持选定的 Navlink?

Navigation.tsx

export const Navigation = ({ userId }: { userId: Id }) => {
  const [ownEvents, setOwnEvents] = useState<EventsPerMonth[]>();
  const [attendedEvents, setAttendedEvents] = useState<EventsPerMonth[]>();
  const { url, path } = useRouteMatch();
  const { push } = useHistory()

  useEffect(() => {
    getCreatedEventsByUserId(userId).then(setOwnEvents);
    getAssistedEventsByUserId(userId).then(setAttendedEvents);
    push(`${url}/created-events`);
  }, [userId, push, url]);

  return (
    <>
      <StyledNavigation>
        <ul>
          <li>
            <StyledNavLink to={`${url}/created-events`} activeClassName="any">
              Eventos creados
            </StyledNavLink>
          </li>
          <li>
            <StyledNavLink to={`${url}/assisted-events`} activeClassName="any">
              Eventos asistidos
            </StyledNavLink>
          </li>
        </ul>
      </StyledNavigation>

      <Switch>
        <ProtectedRoute exact path={`${path}/created-events`}>
          {attendedEvents && <EventsList events={attendedEvents} />}
        </ProtectedRoute>
        <ProtectedRoute exact path={`${path}/assisted-events`}>
          {ownEvents && <EventsList events={ownEvents} />}
        </ProtectedRoute>
      </Switch>
    </>
  );
};

允许吗?

useEffect(() => {
    getCreatedEventsByUserId(userId).then(setOwnEvents);
    getAssistedEventsByUserId(userId).then(setAttendedEvents);
    push(`${url}/created-events`);
  }, [userId, push, url]);

还有其他方法吗?
谢谢!

useEffect 挂钩发出导航操作是完全有效和允许的。虽然,因为看起来这个 Navigation 组件实际上只是调用一些 API 来填充一些本地状态并无条件导航到其中一个子路由,我可能建议使用重定向(REPLACE)而不是导航(PUSH ) 有助于减少历史堆栈条目的操作。

const { replace } = useHistory();

useEffect(() => {
  getCreatedEventsByUserId(userId).then(setOwnEvents);
  getAssistedEventsByUserId(userId).then(setAttendedEvents);
  replace(`${url}/created-events`);
}, [userId, history, url]);

事实上,这个重定向似乎只是为了让用户到达 sub-route。您可以渲染一个 Redirect 来从 path 重定向到 "{path}/created-events".

useEffect(() => {
  getCreatedEventsByUserId(userId).then(setOwnEvents);
  getAssistedEventsByUserId(userId).then(setAttendedEvents);
}, [userId, history, url]);

...

<Switch>
  <ProtectedRoute exact path={`${path}/created-events`}>
    {attendedEvents && <EventsList events={attendedEvents} />}
  </ProtectedRoute>
  <ProtectedRoute exact path={`${path}/assisted-events`}>
    {ownEvents && <EventsList events={ownEvents} />}
  </ProtectedRoute>
  <Redirect to={`${path}/created-events`} />
</Switch>