Reach router navigate updates URL but not component

拥有回忆 提交于 2020-02-24 04:42:53

问题


I'm trying to get Reach Router to navigate programmatically from one of my components. The URL is updated as expected however the route is not rendered and if I look at the React developer tools I can see the original component is listed as being displayed.

If I refresh the page once at the new URL then it renders correctly.

How can I get it to render the new route?

A simplified example is shown below and I'm using @reach/router@1.2.1 (it may also be salient that I'm using Redux).

import React from 'react';

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

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

  return <div />;
};

export default ExampleComponent;

回答1:


I was running into the same issue with a <NotFound defualt /> route component.

This would change the URL, but React itself didn't change:

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;
};

This changes the URL and renders the new route as I would expect:

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

  return null;
};


来源:https://stackoverflow.com/questions/57678103/reach-router-navigate-updates-url-but-not-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!