【发布时间】: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