reactjs - 反应路由器4 url问题
问题描述
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { history } from './history';
import Login from './components/Login';
import Home from './components/Home';
import NotFound from './presentation/NotFound';
import MainContent from './components/MainContent';
import Overview from './components/Overview';
export default () => {
return(
<Router history ={history}>
<Switch>
<Route path="/" component={Login} exact />
<Home>
<Route path="/main" exact component={MainContent} />
<Route path="/admin/:id" exact component={Overview} />
</Home>
<Route component={ NotFound } />
</Switch>
</Router>
);
}
我的 webpack 配置是
const path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './src/main.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',test: /\.js$/,exclude: /node_modules/},
{
test: /\.s?css$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
}, {
test: /\.(png|jpg|gif)$/,
use: [
'file-loader',
],
},{
test: /\.svg$/,
use: ['@svgr/webpack'],
}, {
test: /\.ttf$/,
loader: "file-loader?limit=10000"
}
]
},
devtool: 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(__dirname, 'public'),
historyApiFallback: true
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
__CLIENT__: JSON.stringify(true),
__DEVELOPMENT__: true,
__DEVTOOLS__: true
}),
],
optimization:{}
};
因此,当我登陆/main
ie MainContent 组件时,它会呈现一个ViewComponent
呈现管理员列表的组件,并且单击列表中的单个元素时,它会提供该元素在/admin/:id
路线上的详细视图,该组件运行良好。
但是,如果我直接从地址栏刷新或点击 url,那么最初从中呈现的字体和图像的网络请求
localhost:8080/somerandomid.ttf
现在会从localhost:8080/admin/somerandomid.ttf
抛出 400 错误请求错误中检索,并且样式会更改。
任何人都可以建议如何纠正这个错误。我正在调用一个函数并在单击列表中的元素时传递 id。
this.props.history.push('/admin/' + id);
这ViewComponent
就是连接管理列表export default withRouter(ViewComponent);
以获取 this.props.history.push。
图片网址也是如此。localhost:8080/otherandomid.png 被替换并尝试从 localhost:8080/admin/otherandomid.png 获取 > 并抛出 400 bad request 错误,不显示图像。
解决方案
您需要设置一个基本 URL。
可以通过以下方式完成HtmlWebpackPlugin
:
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
__CLIENT__: JSON.stringify(true),
__DEVELOPMENT__: true,
__DEVTOOLS__: true
}),
new webpack.HtmlWebpackPlugin({
base: '/'
}),
],
或直接在<head>
您的index.html
文件中:
<base href="/">
推荐阅读
- python - Python列表与数组,如果我们知道第一个元素的位置,如何计算内存中的位置
- android - Android Studio:java 和 javax 导入的未解决参考,但项目编译
- sql - 在 Bigquery 中使用 JOIN 进行计数
- google-chrome - 无法在 Google Chrome Linux 中更改权限
- docker - 如何在 Docker 中运行 Hadoop DFSIO MapReduce 基准测试?
- java - 在字符串替换方法中使用 CharSequence 作为参数的原因
- terraform - terraform 中是否有任何特定的资源标签可以在 eventbridge 中创建规则
- python - 是否可以在 python 的 drawcontour 中为特定区域着色?
- python - 在 discord.py-rewrite 中将 Dm 发送给用户命令
- esp32 - 在 ESP32 中运行主程序时如何通过 wifi 接收消息?