9

我试图让到达路由器以编程方式从我的一个组件中导航。URL 已按预期更新,但路由未呈现,如果我查看 React 开发人员工具,我可以看到原始组件被列为正在显示。

如果我在新 URL 处刷新页面一次,则它会正确呈现。

我怎样才能让它渲染新路线?

下面显示了一个简化的示例,我正在使用@reach/router@1.2.1(我正在使用 Redux 也可能很突出)。

import React from 'react';

import { navigate } from '@reach/router';

const ExampleComponent = props => {
  navigate('/a/different/url');

  return <div />;
};

export default ExampleComponent;
4

4 回答 4

2

<NotFound defualt />我在使用路由组件时遇到了同样的问题。

这会改变 URL,但 React 本身并没有改变:

import React from "react";
import { RouteComponentProps, navigate } from "@reach/router";

interface INotFoundProps extends RouteComponentProps {}

export const NotFound: React.FC<INotFoundProps> = props => {
  // For that it's worth, neither of these worked 
  // as I would have expected
  if (props.navigate !== undefined) {
    props.navigate("/");
  }
  // ...or...
  navigate("/", { replace: true });

  return null;
};

这会更改 URL 并按照我的预期呈现新路由:

...
export const NotFound: React.FC<INotFoundProps> = props => {
  React.useEffect(() => {
    navigate("/", { replace: true });
  }, []);

  return null;
};
于 2019-10-11T14:13:00.743 回答
2

是否可以将@reach/routerredux-first-history结合使用?因为我遇到了同样的问题,并且可以通过我的 historyContext 的以下配置来解决它:

import { globalHistory } from "@reach/router";
// other imports

const historyContext = createReduxHistoryContext({
   // your options...
   reachGlobalHistory: globalHistory // <-- this option is the important one that fixed my issue
}

在redux-first-history的 README 中有更多内容

于 2020-05-29T09:27:21.747 回答
2

当我刚开始使用 Reach Router 时,同样的问题也发生在我身上。幸运的是,不久之后找到了解决方案。

在Navigation的 Reach Router 文档中,声明:

Navigate 返回一个承诺,以便您可以等待它。它在 React 完全完成渲染下一个屏幕后解决,即使使用 React Suspense。

因此,await navigate()为我使用它。

import React, {useEffect} from 'react';
import {useStoreState} from "easy-peasy";
import {useNavigate} from "@reach/router";

export default function Home() {
    const {isAuthenticated} = useStoreState(state => state.auth)
    const navigate = useNavigate()

    useEffect(()=> {
        async function navigateToLogin() {
            await navigate('login')
        }
        if (!isAuthenticated) {
            navigateToLogin()
        }
    },[navigate,isAuthenticated])

    return <div>Home page</div>
}
于 2020-07-30T07:03:29.533 回答
-1

尝试并使用 gatsby 导航。它使用到达路由器。它解决了我的问题

从“盖茨比”导入{导航}

于 2021-04-02T20:01:01.733 回答