检测到反应路由器中的后退按钮被按下了

时间:2018-02-28 05:25:47

标签: reactjs react-router

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

反应或反应路由器是否提供了检测后退按钮被按下的方法,以便我可以阻止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))

1 个答案:

答案 0 :(得分:9)

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

componentDidUpdate(){

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

    }