我写了一小段代码来了解React Router,我已经设置了路由belongsTo()
,/
和/aboutme
。问题仅在于/contact
路由有效,其他路由无法渲染。控制台中也没有错误,并且/
路由在/
或localhost:8080/#!/
处工作,而不在localhost:8080/#!
处工作,正如我认为的那样。我正在使用 webpack 4 捆绑文件。我的配置文件是否存在问题,导致此问题?
我尝试访问
的路线
localhost:8080
http://localhost:8080/#!/aboutme
在两种情况下都只渲染根组件
无法获得http://localhost:8080/#!/contact
的掷/ URL
http://localhost:8080/aboutme
的掷骰子无法获得/ url
我不明白我在做什么错,请看一看。
http://localhost:8080/contact
我的webpack配置
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"));
答案 0 :(得分:0)
使用<Switch />
组件只能为一条路线渲染一个组件,并将精确的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"));