【问题标题】:Action Creators Undefined动作创作者未定义
【发布时间】:2020-08-08 01:40:32
【问题描述】:

我是 redux 的新手,我正在尝试通过在我的容器文件中调度 action creator 函数 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)

【问题讨论】:

    标签: react-redux


    【解决方案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
      }
    }
    

    【讨论】:

    • 谢谢。我忘记了!我通常使用类属性转换来避免类中的绑定函数。
    猜你喜欢
    • 2021-03-03
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2015-07-01
    • 2018-03-18
    相关资源
    最近更新 更多