我正在使用React / Redux构建一个“黑客新闻”克隆,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(主页)。有人知道怎么修这个东西吗?我找不到任何真正的文档(或任何其他一般性的问题,而不是特定于OP的特定问题)对React / Redux有任何意义,以及在哪里放置onpopstate
或者做什么来做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?
withRouter HOC在组件内部为您提供历史记录,因此您不使用窗口提供的那个。
即使不使用withRouter,您也应该能够访问window.history。
所以应该是这样的:
const { history } = this.props;
history.push() or history.goBack()