【问题标题】:Reach router navigate updates URL but not component到达路由器导航更新 URL 但不是组件
【发布时间】:2019-12-31 20:05:33
【问题描述】:

我正在尝试让 Reach Router 以编程方式从我的一个组件中导航。 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;

【问题讨论】:

  • 嗨,你知道是什么原因造成的吗?无论使用导航或链接,我都遇到了同样的问题。如果我刷新页面,那么组件就会呈现。

标签: javascript reach-router


【解决方案1】:

我在使用 &lt;NotFound defualt /&gt; 路由组件时遇到了同样的问题。

这会改变 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;
};

【讨论】:

    【解决方案2】:

    您是否可以将 @reach/router 与 redux-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
    }
    

    README of redux-first-history 中的更多信息

    【讨论】:

      【解决方案3】:

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

      在navigate 的 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>
      }
      

      【讨论】:

        【解决方案4】:

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

        从'gatsby'导入{导航}

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-24
          • 1970-01-01
          • 1970-01-01
          • 2017-10-10
          相关资源
          最近更新 更多