Sky*_*n R 6 javascript router refresh reactjs redux
我正在学习 React。我有 4 个子页面的页面,我使用 React 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')
Run Code Online (Sandbox Code Playgroud)
在“应用程序”中,我有导航,在那里我呈现来自 Home、AllHotels 等的其余内容。
有来自 App.jsx 的代码
class App extends Component {
render() {
return (
<div className="app-comp">
<Navigation />
<div> {this.props.children}</div>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我还附上了显示我的问题的 gif。
在后端,如果重要的话,我会使用 Firebase。
提前致谢。
我找到了我的问题的原因。我在我的项目中也使用了 Firebase,它导致了问题。谢谢大家的帮助。
编辑 ================================================== ======================
Mabye 我会写下我是如何解决我的问题的,以及它的原因是什么。所以我在 auth 方法中检查用户是否登录。如果用户获得授权,我就会推/送到 browserHistory。这是错误的,因为每个刷新方法都在执行,然后还调用了重定向。解决方案只是检查在执行身份验证方法期间我是否在登录页面上。如果是登录页面,那么我/将推送到 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');
}
})
Run Code Online (Sandbox Code Playgroud)
我知道这不是很好的解决方案,但它有效,它只是为了学习反应而创建的家庭项目。(顺便说一句,这个项目使用的是旧的反应路由器 3.0,所以现在使用 browserHistory 的概率已被弃用)
检查 Firebase 是否不会与客户端路由发生干扰:P
您可以使用索引路由来实现此目的。
您拥有导航,即应用程序组件中所有页面的布局,因此将其设为根路线。
然后,您希望将家乡路线设为默认路线,因此将其设为索引路线。
您需要从react-router包(从中导入Route)导入IndexRoute。
添加这个-
import { Router, Route, IndexRoute } from 'react-router';
Run Code Online (Sandbox Code Playgroud)
然后让你的路线如下所示。
用这个-
<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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25410 次 |
| 最近记录: |