如何修复React Router中'/action'路由无匹配元素导致的空页面问题?
问题:路由"/action"页面空白,报错叶子路由无元素
utils.ts:874
我完全不知道该如何修复这个问题。
在路径"/action"匹配到的叶子路由没有元素。
这意味着默认会渲染一个值为null的<Outlet />,
从而导致页面"空白"。
以下是我的代码:
import React from 'react'; import '../App.css'; import Card from 'react-bootstrap/Card'; import CardGroup from 'react-bootstrap/CardGroup'; import Logo from './logo.png'; class Action extends React.Component { render() { return ( <div className="App"> <font color="white"><h1>Action Based Shows</h1></font> {/*Hard coded shows in cards */} <CardGroup> <Card bg="dark" text="white"> <a href="https://www.imdb.com/title/tt5675620/"><Card.Img src="http://ayanahaviv.com/wp-content/uploads/2014/11/34-The-Punisher.jpg" /></a> <Card.Body> <Card.Title>The Punisher</Card.Title> 2017-2019 <Card.Text> A rocky start can't keep The Punisher from pushing the boundaries of Marvel's TV universe with a fresh take on the comics-derived action thriller. </Card.Text> </Card.Body> </Card> </div> ); } } export default Action;
解决办法
1. 修复路由配置
报错核心是/action路由未关联你编写的Action组件,需在路由配置文件(通常是App.js或routes.js)中,将组件挂载到对应路径。以React Router v6为例:
import { Routes, Route } from 'react-router-dom'; import Action from './Action'; // 确保导入路径正确 function App() { return ( <Routes> {/* 其他路由 */} <Route path="/action" element={<Action />} /> </Routes> ); } export default App;
2. 修复组件语法错误
你的Action组件中<CardGroup>标签未闭合,这会导致渲染异常,需补上闭合标签:
class Action extends React.Component { render() { return ( <div className="App"> <font color="white"><h1>Action Based Shows</h1></font> {/*Hard coded shows in cards */} <CardGroup> <Card bg="dark" text="white"> <a href="https://www.imdb.com/title/tt5675620/"><Card.Img src="http://ayanahaviv.com/wp-content/uploads/2014/11/34-The-Punisher.jpg" /></a> <Card.Body> <Card.Title>The Punisher</Card.Title> 2017-2019 <Card.Text> A rocky start can't keep The Punisher from pushing the boundaries of Marvel's TV universe with a fresh take on the comics-derived action thriller. </Card.Text> </Card.Body> </Card> </CardGroup> {/* 补上该闭合标签 */} </div> ); } }
内容的提问来源于stack exchange,提问作者RabidHades
相关产品推荐
相关产品推荐

