【发布时间】:2019-02-19 22:23:08
【问题描述】:
我正在使用 React/Redux 构建一个“黑客新闻”克隆 Live Example,但无法使最后的功能发挥作用。我将整个App.js 包裹在BrowserRouter 中,并使用window.history 将withRouter 导入到我的组件中。我在我的 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 有任何意义的真实文档(或任何其他一般性的而不是特定于 OP 特定问题的问题)以及在哪里放置 onpopstate 或在 @987654330 中做什么@ 让它正常工作。
编辑:在下面添加了更多代码
动作创建者:
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);
};
^^^ 这会将我的所有 Redux 状态通过window.history.state 正确记录到控制台,所以我假设我正在正确实现window.history.pushState()。
PostList 组件:
class PostList extends React.Component {
componentDidMount() {
window.onpopstate = () => {
window.history.back();
};
}
(...)
}
我尝试将window.history.back() 更改为this.props.history.goBack(),但没有成功。我的代码有意义吗?我是否从根本上误解了 History API?
【问题讨论】:
标签: reactjs redux react-router browser-history html5-history