简体   繁体   English

页面刷新后,React Router无法正常工作

[英]React Router not working after the page refresh

fellow coders! 同伴们!

I have a react web app with BrowserRouter but when I do a page refresh, it suddenly stops routing anywhere regarding redirects from code. 我有一个带有BrowserRouter的React Web应用程序,但是当我刷新页面时,它突然停止了路由有关代码重定向的任何地方。

The main index.js code looks like this: index.js的主要代码如下所示:

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

The App.js routing is made from free and protected routes - just my way of implementing user authentication: App.js路由是由自由和受保护的路由组成的-这只是我实现用户身份验证的方式:

const freeRoutes = () => (
  <Switch> //My login component
    <Route path='/' component={Signin} /> 
    <Redirect to='/' />
  </Switch>
)

const protectedRoutes = () => (
  <Switch> //The other component from which I use the log out function
    <Route path='/home' component={Home} /> 
    <Redirect to='/home' />
  </Switch>
)

const App = (props) => (
    <div>
      { sessionStorage.getItem("token") ? protectedRoutes() : freeRoutes() }
    </div>
)

May app's Logout function is based on action, which simply removes sessionStorage item. 可能应用程序的注销功能基于操作,该操作仅删除sessionStorage项目。

How do I reproduce the problem and how do I know that my code should be working? 如何重现该问题以及如何知道我的代码应该正常工作?

When I log in and get redirected to Home component and then click logout - everything works fine, I get redirected back to the Login component and I can keep doing this multiple times. 当我登录并重定向到“主页”组件,然后单击“注销”时,一切正常,我被重定向回“登录”组件,并且我可以多次这样做。

However, when I log into my app and while being in Home component refresh the page - the redirections does no longer work. 但是,当我登录到我的应用程序并在Home组件中时,刷新页面-重定向不再起作用。 I've checked if the logout function works, and it really does work - it removes the sessionStorage item, but the redirection does not work and the path stays stuck on localhost:3000/home until I refresh the page again, what then transfers me back to the Login component. 我已经检查了登出功能是否正常工作,并且确实工作了-它删除了sessionStorage项,但是重定向不起作用,并且路径一直停留在localhost:3000 / home上,直到我再次刷新页面为止,然后什么转移了我回到登录组件。

I use: 我用:

 "react": "^16.4.0", "react-redux": "^5.0.7", "react-router-dom": "^4.3.1" 

I've also tried adding < base href="/"> into my index.html as well as historyApiFallback setting into my webpack.config.dev.js. 我还尝试将<base href =“ /”>添加到我的index.html中 ,并将historyApiFallback设置添加到我的webpack.config.dev.js中。

  devServer: { historyApiFallback: true } 

Any suggestions, corrections and ideas would be very appreciated! 任何建议,更正和想法将不胜感激!

PS This project was made using create-react-app PS此项目是使用create-react-app制作的

All sessionstorage variables are destroyed for all open tabs(fresh is part of it as well). 所有打开的标签页的所有sessionstorage变量都被破坏(新鲜也是其中的一部分)。 However, localstorage variables are preserved. 但是,保留了本地存储变量。

So what is happening is when you login, you created a session storage. 因此,发生的事情是在您登录时创建了会话存储。 Once you refresh, it destroyed the session storage, and you still are trying to go to /home , which takes you there. 刷新后,它破坏了会话存储,并且您仍在尝试转到/home ,它将带您到那里。 You are still in /home . 您仍在/home

You can solve the problem in two ways: 您可以通过两种方式解决问题:

  1. change to localstorage 更改为本地存储

  2. take care of this in component. 在组件中注意这一点。 Like in the componetDidmount, you can check if there is a session, if not, trigger a redirect. 像在componetDidmount中一样,您可以检查是否存在会话,如果没有,则触发重定向。

If the issue is happening with a production build on your deployed website (not in testing in your local server) the issue could be with your web.config file. 如果问题出现在您部署的网站上的生产版本中(而不是在本地服务器中进行测试),则问题可能出在您的web.config文件中。 Try adding the following rule to your web.config file: 尝试将以下规则添加到您的web.config文件中:

       <rule name="Rewrite Text Requests" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTP_METHOD}" pattern="^GET$" />
            <add input="{HTTP_ACCEPT}" pattern="^text/html" />
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>

Seems like the issue was caused because the main App component was rendering before the routes are checked with if statement. 似乎是造成此问题的原因,因为在使用if语句检查路由之前,主要的App组件正在渲染。

I then changed the logic of how I push routes - instead of using different switches, I left only one switch with all the routes. 然后,我更改了推路由的逻辑-而不是使用不同的交换机,而是只留下了一个包含所有路由的交换机。 And inside the Login and Home components, I do the check (if authenticated) and use history.push() to redirect. 在Login和Home组件内部,我进行检查(如果已通过身份验证),并使用history.push()进行重定向。

Thus, the problem was not with the router, but with the processes sequence after all. 因此,问题出在路由器上,而不是路由器上。

Thank you all for your answers. 谢谢大家的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM