【问题标题】:Detecting that the back button was pressed in react-router检测到在 react-router 中按下了后退按钮
【发布时间】:2018-08-07 22:00:39
【问题描述】:

我有一个从 api 检索帖子的组件,但每次用户按下后退按钮时,都会触发 componentDidMount 事件并重复 api 调用。

react 或 react-router 是否提供了一种检测后退按钮被按下的方法,以便我可以阻止 api 调用?

import React, { Component } from 'react'
import { fetchData } from '../actions/actions'
import { connect } from 'react-redux'
import { receivePosts } from '../actions/actions'
import { PostList } from '../components/PostList'
import { withRouter } from 'react-router-dom'

class PostListContainer extends Component {


componentDidMount() {            
        this.props.fetchData("posts", receivePosts)
}


render() {
    const { posts, active} = this.props
    return (
        <PostList
            posts={active === '' ? posts : posts.filter( p => p.category === active)}
        />
    )}
}


function mapStateToProps (state) {
    return {
        posts:state.posts,
        active:state.categories.activeFilter
    }
}

function mapDispatchToProps(dispatch)  {
    return {
        receivePosts: () => dispatch(receivePosts()),
        fetchData: (e, h) => dispatch(fetchData(e, h))
    }
}


export default withRouter(connect(mapStateToProps, mapDispatchToProps)(PostListContainer))

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

要检测浏览器中的后退按钮,您可以使用 window.onpopstate 事件,像这样在 componentDidUpdate 中使用它,这对我有用。

componentDidUpdate(){    
  window.onpopstate = e => {
     //your code...
  }
}

【讨论】:

  • 如何防止默认的后退按钮行为并使用您自己的行为?
  • @dan674 已经有一段时间了,但我认为没有默认行为。可能发生的情况是在 componentDidMount 生命周期挂钩中触发了 api 调用。通过检测到后退按钮被按下,我能够使 api 调用有条件。希望这可以帮助。你可以在这里看到代码link
  • 如何区分前进和后退按钮?您上面的代码向前和向后触发。
猜你喜欢
  • 1970-01-01
  • 2016-12-08
  • 2017-06-11
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多