【发布时间】:2021-10-21 12:13:41
【问题描述】:
我正在尝试在我的 React 应用程序中设置路由。我没有收到任何错误,应用程序也没有中断,但是当我导航到新页面时,什么也没有显示。我正在使用 react-router-dom v6 并且 'Switch' 已替换为 'Routes' 并且组件已替换为元素:https://reacttraining.com/blog/react-router-v6-pre/。看来您不需要前导“/”。
在页面底部编辑。
http://localhost:3000/Player 和 http://localhost:3000/*(或除 * 以外的任何内容)都呈现空白屏幕。
这是运行良好的着陆页:
主页.tsx
/** @jsxImportSource @emotion/react */
import React from 'react';
import { css } from '@emotion/react';
import logo from '../assets/cyberpunk.png';
export const HomePage = () => (
<div
css={css`
margin: 10px auto 20px auto;
padding: 30px 20px;
max-width: 1000px;
display: flex;
align-items: center;
justify-content: space-between;
`}
>
<div>
<img
src={logo}
alt="Logo"
css={css`
width: 700px;
margin-left: 130px;
`}
/>
<h2>Players</h2>
<button>Select a toon</button>
</div>
</div>
);
这是播放器页面:
PlayerPage.tsx
import React from 'react';
export const PlayerPage = () => <h2>"One toon"</h2>;
找不到页面的页面:
NotFoundPage.tsx
import React from 'react';
export const NotFoundPage = () => <h2>"Page Not Found"</h2>;
最后,
App.tsx
/** @jsxImportSource @emotion/react */
import React from 'react';
import { css } from '@emotion/react';
import { Header } from './header';
import { HomePage } from './Views/HomePage';
import { fontFamily, fontSize, gray2 } from './Styles';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { PlayerPage } from './Views/PlayerPage';
import { PlayersPage } from './Views/PlayersPage';
import { PlayerCreatePage } from './Views/PlayerCreatePage';
import { NotFoundPage } from './Views/NotFoundPage';
function App() {
return (
<BrowserRouter>
<div
css={css`
font-family: ${fontFamily};
font-size: ${fontSize};
color: ${gray2};
`}
>
<Header />
<Routes>
<Route path="" element={<HomePage />} />
<Route path="Players" element={<PlayersPage />} />
<Route path="Player" element={<PlayerPage />} />
<Route path="Create" element={<PlayerCreatePage />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
</div>
</BrowserRouter>
);
}
export default App;
为什么 NotFoundPage 和 PlayerPage 中的 h2 元素不会显示?这就像我每次都在导航到错误的路线。
我修好了。我重新制作了其中一个页面,如下所示:
function PlayerCreatePage() {
return (
<div style={{ padding: 20 }}>
<h2>About View</h2>
<p>Lorem ipsum dolor sit amet, consectetur adip.</p>
</div>
);
}
export default PlayerCreatePage;
这个确实出现了。这是为什么?其他观点有什么问题?
【问题讨论】:
-
我认为您在所有路径值之前都缺少反斜杠。我也不确定您使用的是哪个版本的 react-router-dom。我期待一个 Switch 组件而不是 Routes,以及“component”Route prop 而不是“element”。
-
@Mary 看起来在 react-router-dom v6 'Switch' 已被 'Routes' 替换。
-
@GrillOwner69420 你能解决这个问题吗?有这方面的更新吗?
标签: javascript reactjs react-router react-router-dom