【问题标题】:Why does my React component not render when using React-Router?为什么我的 React 组件在使用 React-Router 时不呈现?
【发布时间】:2020-02-02 18:25:57
【问题描述】:

我已经在 App.js 中设置了我的 React 路由器。页面组件会渲染。当我点击一个链接时,页面组件将不会呈现,但浏览器中的 URL 会更改为“page/{id}”。为什么是这样?

页面组件:

function Pages(props) {   const managedPages = JSON.parse(localStorage.getItem("managedPages"));   console.log(managedPages);

  return (
    <div>
      <List>
        {managedPages.map(page => (
          <ListItem key={page.id}>
            <Link
              to={`/page/${page.id}`}
              style={{ textDecoration: "none", color: "black" }}
            >
              <ListItemText primary="Teszt Színház" />
            </Link>
          </ListItem>
        ))}
      </List>
      <Route path="/page" component={Page} />
    </div>   ); }

App.js jsx:

 return (
<MuiPickersUtilsProvider utils={MomentUtils}>
        <BrowserRouter>
          <div className="App">
            <BarAndMenu
              userLoginAndDataDownloadCompletedOut={
                this.userLoginAndDataDownloadCompletedOut
              }
            />
          </div>
          <Switch>
            <Route path="/" exact component={OngoingEventList} />
            <Route path="/selectSeat" component={SelectSeat} />
            <Route path="/releasePurpose/:id" component={ReleasePurpose} />
            <Route
              path="/marketingResourceConfigurationAndResult/:id"
              component={MarketingResourceConfigurationAndResult}
            />
            <Route path="/myTickets" exact component={MyTicketList} />
            <Route path="/myTickets/:id" component={MyTicket} />
            <Route path="/auditoriumList/:id" component={AuditoriumSelector} />
            <Route path="/pages" component={Pages} />
          </Switch>
        </BrowserRouter>
</MuiPickersUtilsProvider utils={MomentUtils}>
    );

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    这是因为/page/:id/page 是两种不同的模式,它们不匹配。

    将您的 Route 定义更改为以下内容:

    <Route path="/page/:id" component={Page} />
    

    此外,您在/pages 路由中定义了/page 路由,当您导航到/page:id 时,它不会立即呈现。因此,将路由定义从Pages 组件中提取出来,它应该可以工作。

    https://reacttraining.com/react-router/web/example/url-params

    【讨论】:

    • 我已经这样做了,但页面仍然没有呈现。我在 Page 中也有一个类似的链接,它不使用参数,但也不呈现。
    • 你也可以添加你的 App.jsx 吗?
    • 可能发生的情况是你没有用Router(例如BrowserRouter)包裹整个东西,这是必需的。
    猜你喜欢
    • 2021-08-19
    • 2023-02-03
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 2019-11-23
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多