exo*_*lav 53 javascript routes localhost reactjs react-router
我开始使用react-router v4.<Router>
我的app.js中有一个简单的导航链接(参见下面的代码).如果我导航到localhost/vocabulary
,路由器会将我重定向到正确的页面.但是,当我按下重新加载(F5)之后(localhost/vocabulary
)时,所有内容都会消失并且浏览器报告Cannot GET /vocabulary
.怎么可能?有人能给我任何线索如何解决(正确重新加载页面)?
App.js:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { Switch, Redirect } from 'react-router'
import Login from './pages/Login'
import Vocabulary from './pages/Vocabulary'
const appContainer = document.getElementById('app')
ReactDOM.render(
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/vocabulary">Vocabulary</Link></li>
</ul>
<Switch>
<Route exact path="/" component={Login} />
<Route exact path="/vocabulary" component={Vocabulary} />
</Switch>
</div>
</Router>,
appContainer)
Run Code Online (Sandbox Code Playgroud)
Tyl*_*nis 154
我假设你正在使用Webpack.如果是这样,在webpack配置中添加一些内容应该可以解决问题.具体来说,output.publicPath = '/'
和devServer.historyApiFallback = true
.下面是一个示例webpack配置,下面使用了^并修复了我的刷新问题.如果你对"为什么"感到好奇,这将有所帮助.
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
Run Code Online (Sandbox Code Playgroud)
我在这里写了更多关于这一点 - 使用React Router修复"无法GET/URL"错误(或客户端路由器如何工作)
Wil*_*she 14
只是为了补充Tyler对于仍然在努力解决这个问题的人的回答:
添加devServer.historyApiFallback: true
到我的webpack配置(没有设置publicPath
)修复了我在刷新/返回/转发时看到的404/Can not-GET错误,但仅限于单级嵌套路由.换句话说,"/"和"/ topics"开始正常工作,但除此之外的任何事情(例如"/ topics/whatever")仍然在刷新/等等上投入404.
刚刚遇到了接受的答案:意外的令牌<反应路由器组件中的错误,它为我提供了最后一个缺失的部分./
在我的添加前导到bundle脚本src index.html
已经完全解决了这个问题.
小智 8
它对我有用devServer { historyApiFallback: true }
,只需要添加就可以了,不需要使用publicPath: '/'
用法如:
devServer: {
historyApiFallback: true
},
Run Code Online (Sandbox Code Playgroud)
如果您的应用程序托管在静态文件服务器上,则需要使用 .
import { HashRouter } from 'react-router-dom'
ReactDOM.render((
<HashRouter>
<App />
</HashRouter>
), holder)
Run Code Online (Sandbox Code Playgroud)
适用于 React-router v6 和 Webpack 5
( https://webpack.js.org/configuration/dev-server/#devservermagichtml ):
devServer: {
magicHtml: true,
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.html'),
publicPath: '/',
})
]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27931 次 |
最近记录: |