【问题标题】:Why is this React component page not rendering correctly when an id is passed via the React Router URL?当通过 React Router URL 传递 id 时,为什么这个 React 组件页面不能正确呈现?
【发布时间】:2021-05-23 16:01:13
【问题描述】:

我正在为 React 使用以下依赖项:

"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-helmet": "^6.1.0",
"react-html-parser": "^2.0.2",
"react-icons": "^3.11.0",
"react-live-clock": "^4.0.5",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.3"

我有一个菜单,我可以在其中加载带有和不带有传递 id 的组件 PageHowtos

<Route exact path="/howtos" render={() => <PageHowtos {...this.state.pageProps} />} />
<Route exact path="/howtos/:id" render={() => <PageHowtos {...this.state.pageProps} />} />

当我不在 URL 中发送 id 时,页面呈现正常:

但是当我在 URL 中发送一个 id 时,页面收到了该 id,但它没有正确呈现:

这是 PageHowtos.tsx 页面:

import React, { useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import 'custom/styles/pageHowtos.scss';

const pageTitle = 'Web Developer > Howtos';

interface IProps {
    changeSiteTitle: any
}

interface ParamTypes {
 id: string
}

function PageHowtos(props: IProps) {
    const { id } = useParams<ParamTypes>();
    useEffect(() => {
        props.changeSiteTitle(pageTitle);
    }, []);
    return (
        <div className="page_howtos">
            <Helmet>
                <title>Howtos</title>
            </Helmet>
            <div>
                This is the Howtos page. From URL, id = {id}
            </div>
        </div>
    )
}

export default PageHowtos;

在 URL 中传递 id 时,可能导致页面无法正确呈现的原因是什么?

附录

似乎在传递id 时,页面没有加载Bootstrap 样式(!)。为什么会这样?

【问题讨论】:

  • 渲染方式有什么不正确的地方?
  • @im_baby 我标记了上面的第二张图片以突出显示未正确呈现的内容,即按钮样式有些缺失,图标未正确定位。但是在浏览器中查看呈现的 HTML/CSS,我发现两个页面之间没有区别。
  • 我认为可能是 id 字符串变量有一些 HTML 导致渲染不良,但我确定不是这种情况。
  • 我们能看到样式吗?
  • 我认为问题不在于您正在呈现的页面,看起来不错,上层的其他事情正在发生。

标签: reactjs typescript react-router


【解决方案1】:

我找到了答案。它与 React-Router 本身无关。

我正在使用相对路径加载我的引导文件,并且需要一个斜杠!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多