为什么我的 React 组件仅在使用路由时不渲染?反应路由器-dom V6
Why is my react component not rendering only when using routes? react-router-domV.6
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router } from 'react-router-dom';
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
document.getElementById('root')
);
App.js
import React from 'react';
import { Routes, Route } from "react-router-dom";
import Main from './Pages/Home/Main.js';
import NotFound from './Helpers/NotFound.js';
function App() {
return (
<div className="app-routes">
<Routes>
<Route path="/">
<Main />
</Route>
<Route>
<NotFound />
</Route>
</Routes>
</div>
);
}
export default App;
Main.js
import React from 'react';
import './main.css';
function Main(){
return (
<div className="main-content">
<h1>This is the Main Page</h1>
</div>
);
}
export default Main;
绝对不是组件导入问题,在没有路由的情况下测试并且工作完美,但是当我添加路由或者甚至只是路由本身时,什么都不会呈现。我安装了 react-router-dom v.6
React-router v6 api 已更改。你需要使用 element prop 来渲染组件。
<Routes>
<Route path="/" element={<Main>} />
<Route path="/custom" element={<div>custom</div>} />
<Route path="*" element={<NotFound />}>
</Routes>
react-router-dom@6在路由中使用元素属性来显示组件
To display not found page use path ="*" and add it the end of all the
routes so whenever routes don't match I goes to the not found
(404)page.
<Routes>
<Route path="/" element={<Main />}/>
//all your routes here
<Route path="*" element={ <NotFound />}/> //in the last
</Routes>
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router } from 'react-router-dom';
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
document.getElementById('root')
);
App.js
import React from 'react';
import { Routes, Route } from "react-router-dom";
import Main from './Pages/Home/Main.js';
import NotFound from './Helpers/NotFound.js';
function App() {
return (
<div className="app-routes">
<Routes>
<Route path="/">
<Main />
</Route>
<Route>
<NotFound />
</Route>
</Routes>
</div>
);
}
export default App;
Main.js
import React from 'react';
import './main.css';
function Main(){
return (
<div className="main-content">
<h1>This is the Main Page</h1>
</div>
);
}
export default Main;
绝对不是组件导入问题,在没有路由的情况下测试并且工作完美,但是当我添加路由或者甚至只是路由本身时,什么都不会呈现。我安装了 react-router-dom v.6
React-router v6 api 已更改。你需要使用 element prop 来渲染组件。
<Routes>
<Route path="/" element={<Main>} />
<Route path="/custom" element={<div>custom</div>} />
<Route path="*" element={<NotFound />}>
</Routes>
react-router-dom@6在路由中使用元素属性来显示组件
To display not found page use path ="*" and add it the end of all the routes so whenever routes don't match I goes to the not found (404)page.
<Routes>
<Route path="/" element={<Main />}/>
//all your routes here
<Route path="*" element={ <NotFound />}/> //in the last
</Routes>