【发布时间】: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))
【问题讨论】:
-
谢谢@Shubham Kathri,但以下链接更有帮助:link
标签: reactjs react-router