[英]react-router-dom not working as expected with routes
我正在了解 react-router-dom 库和提供路由的组件,并注意到如下奇怪的行为。
假设我们有我们的 App.js 组件,它返回如下的 JSX 代码。
import './App.css';
import ColorAdder from './ColorAdder';
import {Switch,Route} from 'react-router-dom';
function App() {
return (
<Switch>
<ColorAdder/>
<Route path="/hello" exact>
<p>Hello</p>
</Route>
</Switch>
);
}
export default App;
现在组件ColorAdder.js
还包含具有Path
和如下声明的exact
属性的 Routes。
import { Route } from "react-router-dom";
const ColorAdder = ()=>{
return (
<Route path="/hi" exact>
<p>Hi</p>
</Route>
)
}
export default ColorAdder;
App.js 用<BrowserRouter>
包装,我注意到当我们使用 url http://localhost:3002/hi
测试页面时,它按预期返回了 Hi,但它没有返回任何“http://” localhost:3002/hello'.为什么会这样? 谁能解释一下这种行为,为什么带有路径hello
的Route
即使在Switch
wrapping 下并且具有Path
和exact
属性时也无法识别
下面是使用Index.js
的BrowserRouter
ReactDOM.render(,document.getElementById('render'))
版本:react-router-dom@5,npm - 7.20.3,节点 - v16.7.0
首先,在 app.js 中有路由逻辑加上不要在开关内渲染<ColorAdder/>
而是使用组件属性是这样的:-
你的 App.js: -
import './App.css';
import ColorAdder from './ColorAdder';
import {Switch,Route} from 'react-router-dom';
function App() {
return (
<Switch>
<Route path="/hi" component={colorAdder} exact></Route>
// if you have other routes do like this
<Route path="/hello" component={<p>hello</p>} exact></Route>
// instead of hard coding <p>hello </p> here you can create a separate component that render the helloComponent
</Switch>
);
}
您的 ColorAdder.js:-它应该只返回内容,因为路由逻辑是在 app.js 中完成的
import { Route } from "react-router-dom";
const ColorAdder = ()=>{
return (
<p> h1 </p>
)
}
export default ColorAdder;
注意:- BrowserRouter 应该在 index.js 中,它应该包装应用程序组件
<BrowserRouter>
<App />
</BrowserRouter>,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.