我正在使用React / Redux建立一个{Hacker News“克隆版本Live Example,但无法使这最后一个功能正常工作。我将整个App.js
包裹在BrowserRouter
中,并且已经使用withRouter
将window.history
导入了组件。我正在将我的状态推送到我的API调用操作创建者中的window.history.pushState(getState(), null, `/${getState().searchResponse.params}`)
中。 console.log(window.history.state)
在控制台中显示了我的整个应用程序状态,因此可以正常运行。我猜。在呈现帖子的主要组件中,我有
componentDidMount() {
window.onpopstate = function(event) {
window.history.go(event.state);
};
}
....I also tried window.history.back() and that didn't work
当我按下后退按钮时会发生什么,URL栏将使用正确的上一个URL更新,但是一秒钟之后,页面将重新加载到主索引URL(主页)。有人知道怎么修这个东西吗?我找不到任何对React / Redux以及在何处放置onpopstate
或执行该操作有意义的真实文档(或任何其他常规问题,而不是特定于OP特定问题的其他问题)。 onpopstate
使其正常工作。
编辑:下面添加了更多代码
export const searchQuery = () => async (dispatch, getState) => {
(...)
if (noquery && sort === "date") {
// DATE WITH NO QUERY
const response = await algoliaSearch.get(
`/search_by_date?tags=story&numericFilters=created_at_i>${filter}&page=${page}`
);
dispatch({ type: "FETCH_POSTS", payload: response.data });
}
(...)
window.history.pushState(
getState(),
null,
`/${getState().searchResponse.params}`
);
console.log(window.history.state);
};
^^^这样可以通过window.history.state
将我所有的Redux状态正确地记录到控制台,因此我假设我正确地实现了window.history.pushState()
。
class PostList extends React.Component {
componentDidMount() {
window.onpopstate = () => {
window.history.back();
};
}
(...)
}
我尝试将window.history.back()
更改为this.props.history.goBack()
,但没有用。我的代码有意义吗?我是否从根本上误解了History API?
答案 0 :(得分:0)
withRouter HOC在组件内部为您提供了历史记录作为道具,因此您无需使用窗口提供的内容。
即使不使用withRouter,您也应该能够访问window.history。
所以应该是这样的:
functions.php