问题
When I try to access the URL like for example localhost:8080/edit/12 I get an error on the console and I can't access the id from it, is it the problem in the versions used on the package.json or in the webpack config file?
Component EditExpensePage:
import React from "react";
const EditExpensePage = (props) => {
return (
<div>This is from EditExpensePage component at {props.match.params.id}</div>
);
};
export default EditExpensePage;
Component router AppRouter:
import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import EditExpensePage from "../components/EditExpensePage";
const AppRouter = () => (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route path="/edit/:id" component={EditExpensePage} />
</Switch>
</div>
</BrowserRouter>
);
Webpack config file:
const path = require("path");
module.exports = {
entry: "./src/app.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"],
},
],
},
devtool: "source-map",
devServer: {
contentBase: path.join(__dirname, "public"),
},
};
回答1:
I found the solution by converting the component EditExpensePage
to a class component, and it worked.
import React from "react";
export default class EditExpensePage extends React.Component {
render() {
return (
<div>
This is from EditExpensePage component at {this.props.match.params.id}
</div>
);
}
}
回答2:
When you request localhost:8080/edit/12 you serve the index.html, and presumably, that is done for every resource that doesn't exist on your server (as a fallback). I assume, in the index.html you have the following script tag:
<script src="bundle.js"></script>
This is a relative path. You are actually requesting localhost:8080/edit/bundle.js at this point and because that doesn't exist, you end up serving the index.html as the bundle, which is problematic because it's not valid JavaScript.
You should always use /bundle.js regardless of the current URL. Similarly, you'd always want /styles.css for your CSS.
<link rel="stylesheet" href="/styles.css">
<script src="/bundle.js"></script>
来源:https://stackoverflow.com/questions/61033215/react-js-with-webpack-resource-blocked-due-to-mime-type-mismatch-when-accessing