React Router和浏览器历史记录



我完全迷路了,想问一个关于如何在我的应用程序中实现浏览器历史记录的建议。

有了路由器,我所拥有的只是一个单一的组件,它根据我所在的页面来分配页面。app中的页面和文本是从api获取的,每当我点击一个按钮,api就会再次被调用。

<Router>
<Switch>
<Route to="/" component={Body} />
...

很可能不能正常工作,因为链接标签在按钮上,它们指向/page/number:

const renderPageNumbers = apiPagingSliced.map((links, index)  => {
return <Link key={index} to={`/page/${links.label}`}>
<button key={index} id={links.label} 
onClick={props.handleClick} 
className={(links.active ? "mark-page" : "") + " " + (links.url === null ? "remove-btn" : "")}
>{links.label}
</button></Link>
}
)

我已经设法使它工作,所以我得到"www.webpage.com/page/3"为例。但是当我在浏览器中按回,它只会将url更改为前一页,不做任何其他事情。我如何实现功能向后/向前的历史功能?

首先你应该添加路由参数例如:"/:id">

<Route to="/some_page/:id" component={SomePage} />

然后从react-router:

导入useHistory和UseParams
import { useHistory, useParams } from "react-router-dom";
let { id } = useParams();
let history = useHistory();

<button  onClick={() => history.push(`/some_page/${id}`)}> Go to page </button>

首先你应该给/page/(some number)添加一条路由

这是这样做的:

<Router>
<Switch>
<Route to="/" component={Body} />
<Route to="/page/:id" component={Page} />
...

现在在Page组件中导入一个名为useParams的react router dom钩子

import { useHistory } from 'react-router-dom'
const Page = () => {
const history = useHistory()
//pageID will be equal to the page number
return (
<div>
<button onClick={event => history.goBack`}>Go back!</button>
</div>
)
}

最新更新