【问题标题】:React-Router/Redux browser back button functionalityReact-Router/Redux 浏览器后退按钮功能
【发布时间】:2019-02-19 22:23:08
【问题描述】:

我正在使用 React/Redux 构建一个“黑客新闻”克隆 Live Example,但无法使最后的功能发挥作用。我将整个App.js 包裹在BrowserRouter 中,并使用window.historywithRouter 导入到我的组件中。我在我的 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


    【解决方案1】:

    withRouter HOC 将历史记录作为组件内的道具提供,因此您不要使用窗口提供的道具。

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

    所以应该是这样的:

    const { history } = this.props;
    history.push() or history.goBack()
    

    【讨论】:

    • 我添加了一些代码来帮助可视化我所拥有的以及它是如何设置的
    猜你喜欢
    • 2016-06-09
    • 2018-12-25
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2017-01-13
    • 2021-01-02
    • 2023-03-07
    • 2013-03-02
    相关资源
    最近更新 更多