React-Routing使用history.push()获取404页面

时间:2019-10-17 16:55:55

标签: reactjs react-router

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

我试图通过Redirect来更改history.push,但不走运。我认为重定向不是正确的选择。我认为我的问题与我设置route.js文件的方式有关。

  • Paths.js文件:
In [11]: s = "738ab89ffg"

In [12]: %timeit all(c in string.hexdigits for c in s)
1.59 µs ± 19.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [13]: %%timeit
    ...: try:
    ...:   int(s, 16)
    ...: except ValueError:
    ...:   pass
    ...:
1.25 µs ± 19.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

如上所述,我需要传递类型,因为每次打开相同的组件时,我可能会调用不同的内容。 export const PATHS = { NEWS: '/news', NEWS_SHOWS: type => `/news/last/${type}` } 将添加类似type

的内容
  • Route.js文件:
/latest OR /newest OR /most-read
  • 带有按钮的组件:
<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的404。页面加载时发生错误。

非常感谢您的帮助。谢谢

1 个答案:

答案 0 :(得分:1)

您仅在Route.js中定义了一条路由,请尝试:

[2, 0, 2]
test.docx

[2, 1, 2]
Failed.docx

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

<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>

或者,考虑使用url params代替在路由器中指定每种类型:

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

还建议您使用React Router的Link代替带有onclick = history.push hack的按钮:

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