简体   繁体   English

React Router - 刷新后保持在同一页面

[英]React Router - Stay at the same page after refresh

I'm learning React.我正在学习 React。 I have page with 4 subpages and i use React Router to go through those pages.我的页面有 4 个子页面,我使用 React Router 浏览这些页面。 Everything works fine except for reloading page.除了重新加载页面外,一切正常。 When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.当我从“主页”页面转到“关于”页面或其他页面时,没问题,但是当我刷新页面时,它会再次呈现“关于”页面一秒钟,然后将页面更改为主页(主页是默认/第一页)。我希望它停留在当前呈现的页面上,而不是在每次刷新后返回主页。 There is my code in index.js file where i render whole app and use router: index.js 文件中有我的代码,我在其中呈现整个应用程序并使用路由器:

<Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/home" component={App}> 
            <Route path="/" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')

In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.在“应用程序”中,我有导航,在那里我呈现来自 Home、AllHotels 等的其余内容。

There is code from App.jsx有来自 App.jsx 的代码

class App extends Component {

render() {
    return (
        <div className="app-comp">
            <Navigation />
            <div> {this.props.children}</div>
        </div>
    )
  }
}

I also attach gif which shows my problem.我还附上了显示我的问题的 gif。

https://gifyu.com/image/boMp https://gifyu.com/image/boMp

In backend i use Firebase if it's important.在后端,如果它很重要,我会使用 Firebase。

Thanks in advance.提前致谢。

I found the reason of my problem.我找到了问题的原因。 I use also Firebase in my project and it causes the problem.我在我的项目中也使用了 Firebase,它导致了问题。 Thanks guys for help.谢谢大家的帮助。

EDIT ======================================================================编辑 ================================================= =====================

Mabye I will write how I've fixed my problem and what was the reason of it. Mabye 我会写下我是如何解决我的问题的,以及它的原因是什么。 So i was checking if user is logged in or not in auth method.所以我在 auth 方法中检查用户是否登录。 And there if user was authorized I was pushing / to browserHistory.如果用户获得授权,我就会将/推送到 browserHistory。 It was mistake because every refresh method was executing and then also redirection was called as well.这是错误的,因为每个刷新方法都在执行,然后也调用了重定向。 Solution is just to check if during executing auth method I'm on Signin page or not.解决方案只是检查在执行身份验证方法期间我是否在登录页面上。 If it is Signin page then I'm pushing / to browserHistory but if not then just don't push anything.如果它是 Signin 页面,那么我将/推送到 browserHistory,但如果不是,则不要推送任何内容。

    firebaseApp.auth().onAuthStateChanged(user => {
     if (user) {
        let currentPathname = browserHistory.getCurrentLocation().pathname;
        if( currentPathname === "/" || currentPathname === "/signin"){
          browserHistory.push('/');
        }
        const { email } = user;
        store.dispatch(logUser(email));
     }
     else {
        browserHistory.replace('/signin');
     }
    })

I know that it's not pretty solution but it works and it was only home project which was created to learn react.我知道这不是很好的解决方案,但它确实有效,而且它只是为学习反应而创建的家庭项目。 (btw this project is using old react router 3.0 so probalby now using browserHistory is deprecated) (顺便说一句,这个项目使用的是旧的 React Router 3.0,所以现在使用 browserHistory 的概率已被弃用)

Check that firebase does not interfares with the client side routes:P检查 firebase 是否不干扰客户端路由:P

You can use Index routes to achieve this.您可以使用索引路由来实现这一点。

You have your navigation ie the layout of all pages in your app component so make it the root route.你有你的导航,即你的应用程序组件中所有页面的布局,所以让它成为根路由。

Then you want your home route to be your default route so make it your Index route.然后你想让你的家路线成为你的默认路线,所以让它成为你的索引路线。

You need to import IndexRoute from react-router package (from which you import Route).您需要从 react-router 包(从中导入路由)导入 IndexRoute。

Add this-添加这个-

import { Router, Route, IndexRoute } from 'react-router';

and then make your routes like below.然后像下面这样制作你的路线。

Use this-用这个-

<Provider store={store}>
    <Router history={browserHistory}>
        <Route path="/" component={App}> 
            <IndexRoute component={Home} />
            <Route path="/home" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')

it's a Server-side vs Client-side issue check the following thread, it might give you some insights.. React-router urls don't work when refreshing or writting manually这是服务器端与客户端问题检查以下线程,它可能会给你一些见解.. React-router url 在刷新或手动写入时不起作用

Below example you can refer for:您可以参考以下示例:

  • React Router Navigation反应路由器导航
  • Browser Refresh Issue.浏览器刷新问题。
  • Browser Back Button Issue.浏览器后退按钮问题。

Please make sure you have installed react-router-dom请确保你已经安装了react-router-dom

If not installed.如果没有安装。 Use this command to install npm i react-router-dom使用此命令安装npm i react-router-dom

index.js索引.js

   import React from "react";
   import ReactDOM from "react-dom";
   import { BrowserRouter, Route, Switch } from "react-router-dom";

   import Page1 from "./Page1";
   import Page2 from "./Page2";

    const rootElement = document.getElementById("root");
    ReactDOM.render(
      <BrowserRouter>
       <Switch>
        <Route exact path="/" component={Page1} />
        <Route path="/page2" component={Page2} />
      </Switch>
      </BrowserRouter>,
      rootElement
    );

Page1.js Page1.js

   import React from "react";
   import {Link } from "react-router-dom";

    function Page1() {

        return (
          <div>
            <p>
              This is the first page.
              <br />
              Click on the button below.
            </p>
            <Link to="/page2"><button>
              Go to Page 2 
            </button>
            </Link>
          </div>
        );

    }

    export default Page1;

Page2.js Page2.js

   import React from "react";

   function Page2() {

        return (
          <div>
            <p>This is the second page.</p>
          </div>
        );

    }

    export default Page2;

Add into your webpack.config.js this option将此选项添加到您的webpack.config.js

devServer: {
    historyApiFallback: true
},

Route tag returns the first matching component.路由标签返回第一个匹配的组件。 I think you have interchanged the paths of home and app component.我想你已经互换了 home 和 app 组件的路径。

try this.试试这个。

<Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/" component={App}> 
            <Route path="/home" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')

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

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