[英]React-router v4 Page Refresh Not Working
我可能錯過了歷史記錄或其他什么,但當我刷新子路徑上的頁面,如/login
或任何其他路線,我得到:
403禁止
代碼:AccessDenied消息:訪問被拒絕RequestId:075CAA73BDC6F1B9 HostId:O1n36xVCoeu / aLaSMrtCkAFZruWk5ZcO4RIrznEhvUxdu8lFEhL0XcKw2L4W4J7VYYet + HDv8tc =
請記住,只要我不刷新,路線就可以正常工作。
所以我想去/
(主頁)。 在它上面,我有一個超鏈接 ,映射到我的react-router路由中的路徑/login
。 我單擊超鏈接,它工作正常,根據我的react-router路由呈現/ login控件。 只有當我刷新任何頁面時,我才會得到上面的錯誤。
此外,當我同步我的存儲桶時,我正在對其進行公開讀取,因此不確定為什么我收到此權限錯誤:
aws s3 sync --acl public-read build s3://${bkt}
以下是一些路線和組件的示例:
<Provider store={store}>
<Layout>
<Switch>
<Route component={Home} exact path='/' />
<ProtectedRoute component={
DashboardContainer} path='/dashboard' />
<Route component={LoginContainer} path='/login' />
<Route component={NotFound} path='*' />
</Switch>
</Layout>
</Provider>
LoginContainer
import { connect } from 'react-redux'
import React, { Component } from 'react'
const _ = require('lodash')
...
import Login from '../components/auth/Login/Login'
class LoginContainer extends Component {
constructor(props) {
super(props)
this.handleEmailInput = this.handleEmailInput.bind(this)
... rest of the handlers
}
async handleLoginPressed(e) {
e.preventDefault()
this.validateForm()
await this.props.authenticate(this.state.email, this.state.password)
if(this.props.isAuthenticated) {
this.props.history.push('/dashboard')
return
}
... more code
render(){
return(
<div>
<Login
login={this.handleLoginPressed}
/>
</div>
)
}
}
const mapStateToProps = state => ({
token: state.auth.token
})
export const mapDispatchToProps = {
authenticate: AuthAsyncActions.authenticate
}
export { Login }
export default connect(mapStateToProps, mapDispatchToProps)(LoginContainer)
現在我遺漏了一堆重復的代碼,這基本上顯示我在這里唯一的路由是,如果他們成功登錄,他們被重定向到/dashboard
。 問題不在於,重定向工作正常。 無論何時我在我正在打開的任何頁面上刷新,它都不會再次重新路由。
這是因為您的服務器嘗試直接轉到該URL。 您有兩種選擇:
使用react-router v4提供的哈希路由器 。 路線現在看起來像這樣: http://example.com/#/somePage
: http://example.com/#/somePage
如果您不想在URL上添加#,則必須更改服務器行為。 對於不同的服務器,此配置會發生變化。 在開發模式下,如果您使用的是webpack-dev-server,則只需啟用historyApiFallback
。 在生產模式下,搜索如何使用您將使用的服務器重定向403/404響應。
客戶端和服務器端路由之間存在差異。 這已被廣泛的帖子和其他地方所涵蓋。 基本上,如果您的客戶端反應應用程序將它們重定向到某個路由,這與他們在瀏覽器中手動輸入該路由(它與服務器聯系並嘗試獲取該SPECIFIC路由)不同。
因此,如果您在前端有路線,請說:
<Route component={Potato} exact path='/potato' />
但是在你的后端,你沒有處理對所述路徑的請求的東西,然后手動轉到該URL或在該URL上刷新將導致你的應用程序自行停頓。
確保你的后端有一個捕獲所有路線,如下所示:
app.get('*', (request, response) => {
response.sendFile(path.resolve(__dirname, 'index.html'))
});
實質上,捕獲只返回index.html的所有路由
另外一定要查看客戶端與服務器端路由,這將導致頁面刷新問題,並使用React路由器手動導航到某些URL
當我的創建反應應用程序部署到heroku時,我遇到了類似的問題,該應用程序工作正常,直到刷新子路由。 我修復它的方法是在我的根目錄中添加此文件。 不確定這是否會對你有所幫助。
static.json
{
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.