【问题标题】:React Router always renders NotFound default componentReact Router 总是渲染 NotFound 默认组件
【发布时间】:2021-02-08 00:10:55
【问题描述】:

我一直在互联网上搜索解决方案,但很遗憾我来这里寻求帮助。问题是 URL 发生了变化,但 Route 中的相应组件没有呈现,而是呈现了 NotFoundPage

这是App.js Router 代码:

<Router history={history}>
   <Switch>
     <PrivateRoute exact path="/" component={HomePage} />
     <Route path="/login" component={LoginPage} />
     <Route path="/register" component={RegisterPage} />
     <Route component={NotFoundPage}/>
   </Switch>
</Router>

这里是PrivateRoute 代码:

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

export const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
        localStorage.getItem('user')
            ? <Component {...props} />
            : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
    )} />
)

我面临的问题是,当我转到 / 时,NotFoundPage 被呈现而不是 LoginPage URL 正确重定向并更改为 /login。但是当我刷新时,LoginPage 被渲染了。同样,当我单击从LoginPage/register 的链接时,URL 会发生变化,但RegisterPage 不会呈现相同的NotFoundPage

【问题讨论】:

  • 你试过在登录和注册时输入精确吗?
  • 是的,我试过了,但没用。
  • 你能在 (codesandbox.io) 上以最小版本重现这个问题吗??
  • 好的。但是为了测试你可以打开 BroswerRouter 然后我们可以检查这个线索
  • 我切换到BrowserRouter 并且工作正常,但我想知道为什么Router 实现会出现错误。

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


【解决方案1】:

在 github 上贡献期间,我们想出了解决方案。

这种奇怪的行为源于使用自定义历史记录。

const customHistory = createBrowserHistory();

ReactDOM.render(<Router history={customHistory} />, node);

当它被使用时,路由器不会对位置路径的变化做出反应。 直到你不添加:

<Switch location={window.location}>

根据文档,默认情况下 switch 中的位置设置为窗口。位置,但由于某种原因,当您不使用 BroswerRouter 或 StackRouter 而只是路由器时,当我们直接设置位置时,它开始工作。

【讨论】:

    猜你喜欢
    • 2017-04-17
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2017-12-29
    相关资源
    最近更新 更多