React-Redux:动作创建者未定义

时间:2018-01-22 22:03:02

标签: react-redux

我是redux的新手,我尝试通过在容器文件中调度动作创建函数fetching()来更新我的应用程序状态。当我尝试运行我的应用程序时,我得到一个"无法读取属性'取出'未定义"错误。那是为什么?

//popular reducer
const FETCHING = 'FETCHING'

export function fetching() {
  return {
    type: FETCHING,
  }
}

const initialState = {
  isFetching: false,
}

export default function popular(state = initialState, action) {
  switch (action.type) {
    case FETCHING:
      return {
        isFetching: true,
      }
    default:
      return state
  }
}

//Popular Container
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as popularActionCreators from 'redux/popular'
import PropTypes from 'prop-types'

class PopularContainer extends React.Component {

  handleFetch() {
    this.props.fetching() //Cannot read property 'fetching' of undefined
  }  
}

PopularContainer.propTypes = {
  isFetching: PropTypes.bool.isRequired,
  fetching: PropTypes.func.isRequired,
}

function mapStateToProps(state) {
  return {
    isFetching: state.isFetching
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(popularActionCreators, dispatch)
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PopularContainer)

1 个答案:

答案 0 :(得分:1)

根据错误,它不是未定义的动作创建者,而是this.props

您没有显示调用handleFetch()的位置,但很可能需要将其绑定到类实例。 https://reactjs.org/docs/handling-events.html

class PopularContainer extends React.Component {
  constructor(props) {
    super(props);
    this.handleFetch = this.handleFetch.bind(this);
  }

  handleFetch() {
    this.props.fetching()
  }

  render() {
    // Your render method here
  }
}