【问题标题】:React Router: <Redirect push> doesn't update browser urlReact Router:<Redirect push> 不更新浏览器 url
【发布时间】:2020-09-01 23:02:10
【问题描述】:

我正在学习 React 制作一个小型单页应用程序。今天刚刚添加了 react-router-dom 并将其构建为路由和私有路由。一切都很好,除了一件事:当用户在浏览器栏中输入格式错误的 url 时,用户应该被重新路由到索引(WORKS!),但浏览器 url 栏不会在此重定向上更新。奇怪的是,当我在未经授权的情况下访问私有路由时,重定向确实会更新 url 栏。我错过了什么?

router.js:

const PrivateRoute = ({auth: authenticated, component: Component, ...rest}) => (
    <Route {...rest} render={(props) => (
        authenticated === true
            ? <Component {...props} />
            : <Redirect to='/login/'/>
    )}/>
);

export default function Router() {

    const auth = useSelector(isAuthenticated);

    return (
        <Switch>
            <PrivateRoute auth={"auth"} path={"/dashboard/"} component={DashboardContainer}/>
            <Route path={"/about/"} component={AboutContainer}/>
            <Route path={"/login/"} component={LoginContainer}/>
            <Route path={"/terms/"} component={TermsContainer}/>
            <Route path={"/"} component={IndexContainer}/>
            <Redirect push to={"/"}/>
        </Switch>
    );
}

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom


    【解决方案1】:

    我认为您的问题是由于未指定路径应为exact matches,因此任何路由都将与您指定为的路由匹配:

    <Route path={"/"} component={IndexContainer}/>
    

    尝试将 exact 属性添加到您的所有路由(重定向除外),您应该会正确地重定向到具有正确 URL 的主页。

    更多关于确切道具的详细信息:React : difference between <Route exact path="/" /> and <Route path="/" />

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      • 2016-10-11
      • 1970-01-01
      • 2016-01-27
      • 2017-12-29
      • 1970-01-01
      相关资源
      最近更新 更多