我正在使用react-router在React应用程序中学习页面导航
这是我的package.json
{
"name": "tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --inline --content-base .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Rahul Shivsharan",
"license": "ISC",
"dependencies": {
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1"
},
"devDependencies": {
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.4",
"@babel/plugin-proposal-class-properties": "^7.3.4",
"@babel/preset-env": "^7.3.4",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"http-server": "^0.11.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3",
"webpack-dev-server": "^3.2.1"
}
}
这是我的App.js
import React from "react";
import {Link} from "react-router";
export default class App extends React.Component{
render(){
return <div>Hello, React Router !!</div>
}
}
这是Repos.js
import React from "react"
export default class Repos extends React.Component{
render(){
return <div>Repos rendered !!!</div>
}
}
这是About.js
import React from "react"
export default class About extends React.Component{
render(){
return <div>About to be !!</div>
}
}
这是index.js
import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter,Route, Switch} from "react-router-dom";
import App from "./modules/App";
import Repos from "./modules/Repos";
import About from "./modules/About";
ReactDOM.render(
(<BrowserRouter>
<Switch>
<Route path="/" component={App} />
<Route path="/repos" component={Repos} />
<Route path="/about" component={About} />
</Switch>
</BrowserRouter>), document.getElementById("app"));
这是我的index.html
<!DOCTYPE html public "storage">
<html>
<head>
<meta charset="UTF-8">
<title>My First React Router App</title>
</head>
<body>
<div id="app"></div>
<script src="./bundle.js"></script>
</body>
</html>
这是我的webpack.config.js
module.exports = {
"entry" : "./index.js",
"output" : {
"filename" : "bundle.js",
"publicPath" : ""
},
"module" : {
"rules" : [{
"test" : /\.js$/,
"exclude" : /node_modules/,
"loader" : "babel-loader",
"query": {
"presets": ['@babel/react', '@babel/preset-env'],
"plugins": ['@babel/proposal-class-properties']
}
}]
}
}
我的问题是我何时开始使用服务器
npm start
在浏览器中加载 您好,React Router !!
当我这样做时 http://localhost:8081/about
它显示, 无法获取/ about
加载 无法获取/ repos
为什么我无法加载默认路径以外的其他路径?
请问我是否做错了什么,
答案 0 :(得分:1)
您需要启用historyApiFallback
,以便webpack-dev-server将为当前正在发出index.html
响应的所有路由提供404 Not Found
文件。
webpack.config.js
module.exports = {
entry: "./index.js",
output: {
filename: "bundle.js",
publicPath: ""
},
devServer: {
historyApiFallback: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ["@babel/react", "@babel/preset-env"],
plugins: ["@babel/proposal-class-properties"]
}
}
]
}
};