【问题标题】:React Router shows blank page until refreshReact Router 显示空白页面,直到刷新
【发布时间】:2021-09-23 18:22:29
【问题描述】:

我正在学习 React,这个项目涉及 React Router。我已经阅读了许多教程,但无法让它们适用于我的项目

基本上,问题在于我的 React 路由在 URL 更改和页面更改时起作用,但它会更改为空白 index.html,除非重新加载,否则它可以正常工作。

创建 accessToken 时,我的 App.js 呈现 <Profile />

  return (
    <BrowserRouter>
      <AppContainer>
        <GlobalStyle />
          <Switch>
            <Route exact path ='/' component={withRouter(accessToken ? Profile : Login)} />
            <Route exact path ='/playlist' component={withRouter(Playlist)} />
          </Switch>
      </AppContainer>
    </BrowserRouter>
  );

&lt;Profile /&gt; 有指向&lt;Playlist /&gt; 的链接:

    return (
        <Wrapper>
            <Banner user={user} />
            <Link to='/playlist'>Find New Music</Link>
            <Favorites history={history} />
        </Wrapper>
    );

现在只是一个模板:

const Playlist = () => {
    return <h1>Hello</h1>
}

工作,并重定向到 localhost:3000/playlist,但该路由显示白屏。刷新时,&lt;h1&gt;Hello&lt;/h1&gt; 会正确显示。有谁知道为什么会发生这种情况?

【问题讨论】:

  • 你可以尝试交换路线的顺序吗?我想我有类似的事情发生在我身上,因为订单。
  • 你能在codesandbox.io 中复制它吗?
  • 订单似乎并不重要,我尽我所能在代码和框中重新创建它(我的应用程序有一个 Spotify OAuth 的后端,大多数组件都需要它,所以它被掏空了)但路由在那里工作.我唯一的另一个想法是它可能在后端本身,但基本上逐行注释掉潜在的罪魁祸首:app.get('*', function (request, response) { response.sendFile(path.resolve(__dirname, '../client/public', 'index.html')); 并不能解决问题。如果有帮助,我愿意发布任何和所有代码,这只是一个个人项目

标签: javascript reactjs frameworks router


【解决方案1】:

发现错误。

useEffect(() => window.location.hash = '', []);

中断路由。这是一个隐藏在 Profile.jsx 组件中的针对不同问题的快速修复,我将不得不寻找更好的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-31
    • 2022-07-21
    • 2020-05-22
    • 1970-01-01
    • 2015-11-28
    • 2020-02-20
    • 2021-04-15
    • 2022-03-23
    相关资源
    最近更新 更多