javascript - React 路由器不会渲染组件
问题描述
我写了一小段代码来了解反应路由器,我已经设置了路由/
,/aboutme
并且/contact
. 问题只是/
路线有效,其他路线不会渲染。控制台中也没有错误,并且/
路由可以正常工作localhost:8080/#!/
或localhost:8080/#!
不正常工作,localhost:8080
就像我想象的那样。我正在使用webpack 4来捆绑文件。我的配置文件是否有问题导致此问题?
我尝试在两种情况下都只渲染根组件来
访问路由throws cannot get/url throws cannot get/url
http://localhost:8080/#!/aboutme
http://localhost:8080/#!/contact
http://localhost:8080/aboutme
http://localhost:8080/contact
我不明白我做错了什么,请看一下。
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from 'react-router-dom'
import Route from 'react-router-dom/Route'
const root= (props) => {
return (
<p>hello</p>
)
}
const about= (props) => {
return (
<p>About me -_-</p>
)
}
const contact= (props) => {
return (
<p>contact info</p>
)
}
const App = () => {
return (
<Router>
<div>
<Route path="/" exact component={root} />
<Route path="/aboutme" exact component={about} />
<Route path="/contact" exact component={contact} />
</div>
</Router>
)
}
ReactDOM.render(<App />, document.getElementById("index"));
我的 webpack 配置
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');
const htmlPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [htmlPlugin]
};
解决方案
使用<Switch />
Component 为一个路由只渲染一个组件,并将确切的 prop 传递给 Route,它只有在匹配完整路径时才会渲染。
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Switch } from "react-router-dom";
import Route from "react-router-dom/Route";
const root = props => {
return <p>hello</p>;
};
const about = props => {
return <p>About me -_-</p>;
};
const contact = props => {
return <p>contact info</p>;
};
const pageNotFound = props => {
return <p>page not found.</p>;
};
const App = () => {
return (
<Router>
<Switch>
<Route path="/" exact component={root} exact />
<Route path="/aboutme" exact component={about} exact />
<Route path="/contact" exact component={contact} exact />
<Route component={pageNotFound} />
</Switch>
</Router>
);
};
ReactDOM.render(<App />, document.getElementById("index"));
推荐阅读
- xamarin.forms - 想在数据库 MVVM 中添加一些东西
- ios - 适用于 iOS 7+ 的 swift 版本
- makefile - 为什么 make 命令在这里失败
- bokeh - Bokeh MultiLine p.add_tools(HoverTool(), renderers = [multiline]) 不工作
- angular - 如何在 Angular 6 中编辑材料日期选择器中的日期格式?
- javascript - lint 双逗号数组
- dialogflow-es - 当我的对话流培训页面充满 GOOGLE_ASSISTANT_WELCOME 时是否正常?
- mysql - 如何仅返回列的特定部分?
- python - macOS 中导入 PycURL 报错
- ibm-cloud-infrastructure - SoftLayer_Location/getDatacenters API 对不同数据中心的响应不一致