【问题标题】:React-Routing getting 404 page using history.push()React-Routing 使用 history.push() 获取 404 页面
【发布时间】:2019-10-18 04:40:44
【问题描述】:

我需要通过点击打开我的新闻页面的子页面。目前我可以使用 history.push 打开新的 URL,但它返回一个 404 页面。

我尝试使用 Redirect 更改 history.push,但没有成功。我不认为重定向是正确的选择。我认为我的问题与我设置 route.js 文件的方式有关。

  • Paths.js 文件:
export const PATHS = {
  NEWS: '/news',
  NEWS_SHOWS: type => `/news/last/${type}`
}

正如您在上面看到的,我需要传递类型,因为每次打开同一个组件时,我可能会调用不同的内容。 type 将添加类似/latest OR /newest OR /most-read 的内容

  • Route.js 文件:
<Switch>
    <UniqueRoute exact path={PATHS.NEWS} component={News} />    
</Swicth>
  • 带按钮的组件:
import React from 'react';
import { withRouter } from 'react-router-dom';

import { PATHS } from '../../constants';
import Button, { VARIANTS as BUTTON_VARIANTS } from '../../components/Button';

const ViewMoreButton = ({ history, type }) => (
  <Button
    onClick={() => history.push(PATHS.NEWS_SHOWS(type))}
  />
);

export default withRouter(ViewMoreButton);
  • 点击后,页面 URL 为:
localhost:3000/news/last/latest 
OR
localhost:3000/news/last/newest
etc... 

目前,我通过上述任何 URL 得到 404。页面加载时出错。

非常感谢任何帮助。谢谢

【问题讨论】:

  • 嗯,当然你得到的是 404,Route.js 只包含一个路由 (/news),而不是任何你想要导航到的路由 (/news/last/${type})
  • 如果我添加 它返回一个错误。关于 str.slice 的标准 React 错误。您能建议如何配置 Route.js 和 Paths.js 吗?
  • 在您传递一个函数而不是函数的结果(字符串)时也是预期的。我将在答案中发布对 Route.js 的建议。

标签: reactjs react-router


【解决方案1】:

你在 Route.js 中只定义了一个路由,试试:

<Switch>
    <UniqueRoute exact path={PATHS.NEWS} component={News} /> 
    <UniqueRoute exact path={PATHS.NEWS_SHOWS('latest')} component={NewsShows} />   
    <UniqueRoute exact path={PATHS.NEWS_SHOWS('newest')} component={NewsShows} />   
    <UniqueRoute exact path={PATHS.NEWS_SHOWS('most-read')} component={NewsShows} />      
</Switch>

或者,如果您想轻松扩展更多类型,则更优雅一点:

<Switch>
    <UniqueRoute exact path={PATHS.NEWS} component={News} /> 
    {['latest', 'newest', 'most-read'].map(type => 
      <UniqueRoute exact path={PATHS.NEWS_SHOWS(type)} component={NewsShows} />
    )}     
</Switch>

或者,考虑使用url params,而不是指定路由器中的每种类型:

<Switch>
    <UniqueRoute exact path={PATHS.NEWS} component={News} /> 
    <Route path="/news/last/:type" component={NewsShows} />  
</Switch>

还建议使用 react 路由器的 Link 而不是带有 onclick=history.push hack 的按钮:

const ViewMoreButton = ({ history, type }) => (
  <Link to={PATHS.NEWS_SHOWS(type)}> link text </Link> 
);

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 2021-10-30
    • 2021-08-12
    • 2018-07-11
    • 2017-09-21
    • 2019-08-26
    • 2018-08-17
    • 1970-01-01
    • 2021-02-01
    相关资源
    最近更新 更多