How preserve query string and hash fragment, in React-Router 4 <Switch><Redirect>?

我的未来我决定 提交于 2019-12-06 04:57:25

Until the <Redirect /> component gets its own history subscriber, you can make your own:

const RouteAwareRedirect = props => (
  <Route render={routeProps => 
    <Redirect to={props.to(routeProps)} />
  }/>
)

Then use that where ever you want:

<RouteAwareRedirect to={({ location }) => ({ 
  // use location.pathname, etc .. 
}) />

If there's no other way (apparently there isn't, see Azium's answer) ... then this works :- ) at least with exact and strict both true (haven't tested other combos).

Use like so: (and it'll change the path only, not query string or hash)

RedirPath({ path: '/', to: '/latest', exact: true })

and works in a <Switch> with no <Route> above. There's a <Route> inside instead :- P You need to remove dieIf.

License: MIT. (Not CC0.)

/**
 * Redirects the URL path only — preserves query string and hash fragment.
 */
export function RedirPath(props: { path: string, to: string, exact: boolean, strict?: boolean }) {
  // @ifdef DEBUG
  dieIf(props.to.indexOf('?') >= 0, 'TyE2ABKS0');
  dieIf(props.to.indexOf('#') >= 0, 'TyE5BKRP2');
  // @endif
  const path = props.path;
  const exact = props.exact;
  const strict = props.strict;
  return Route({ path, exact, strict, render: (routeProps) => {
    return Redirect({
      from: path, exact, strict,
      to: {
        pathname: props.to,
        search: routeProps.location.search,
        hash: routeProps.location.hash }});
  }});
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!