【问题标题】:How to make React Router render NotFound when there is nothing to display?当没有可显示的内容时,如何使 React Router 呈现 NotFound?
【发布时间】:2021-07-06 10:34:13
【问题描述】:

我正在使用 React Router 构建博客。获取博文后,我将结果分页到页面上:localhost:8080/category/general/4

我在这种情况下,我在结果的最后一页。假设有人去了 localhost:8080/category/general/5 并且没有从 Pagination 返回的帖子要显示。

预期行为:NotFound 组件被渲染。 实际行为:呈现类别页面时没有博客文章。

我如何让 React 知道某个页面不存在,因为有关页面数量的信息位于 Pagination 组件中?

App.js 中的路由:

<Switch>
    <Redirect exact from="/" to="/home/1" />
    <Route path="/home/:page?" component={HomePage} />
    <Route path="/category/:category/:page?" component={CategoryPage} />
    <Route component={NotFoundPage} />
</Switch>

分页.js

const Pagination = (props) => {
    const { page = 1 } = useParams();
    const {
        children, path, limit = 5,
    } = props;
    const begin = limit * (page - 1);
    const end = limit * page;

    const pagesTotal = Math.ceil(children.length / limit);

    const links = new Array(pagesTotal).fill(0).map((link, index) => (
        <li key={index}>
            <Link to={`${path}${index + 1}`}>{index + 1}</Link>
        </li>
    ));

    return (
        <div>
            {children.slice(begin, end)}
            <ul className="pagination-links--container">{links}</ul>
        </div>
    );
};

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom router


    【解决方案1】:

    在 CategoryPage 中处理

    props.match.page < maxPageNumber? <regularPage />: <NotFoundPage/>
    

    【讨论】:

      猜你喜欢
      • 2021-06-13
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2022-06-12
      • 2018-10-03
      • 1970-01-01
      • 2017-12-08
      相关资源
      最近更新 更多