React-Router / Redux浏览器后退按钮功能

时间:2019-02-19 22:23:08

标签: reactjs redux react-router browser-history html5-history

我正在使用React / Redux建立一个{Hacker News“克隆版本Live Example,但无法使这最后一个功能正常工作。我将整个App.js包裹在BrowserRouter中,并且已经使用withRouterwindow.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()

PostList组件:

class PostList extends React.Component {
  componentDidMount() {
    window.onpopstate = () => {
      window.history.back();
    };
  }

(...)

}

我尝试将window.history.back()更改为this.props.history.goBack(),但没有用。我的代码有意义吗?我是否从根本上误解了History API?

1 个答案:

答案 0 :(得分:0)

withRouter HOC在组件内部为您提供了历史记录作为道具,因此您无需使用窗口提供的内容。

即使不使用withRouter,您也应该能够访问window.history。

所以应该是这样的:

functions.php