【问题标题】:react-redux mapDispatchToProps functions undefined on connected componentreact-redux mapDispatchToProps 函数在连接组件上未定义
【发布时间】:2018-04-05 14:56:30
【问题描述】:

看起来我应该能够通过通常命名的 mapDispatchToProps 函数将我的调度处理函数映射到连接组件的道具(在我的示例列表中)。在我的 List 组件中,我很困惑为什么 this.props.a 是未定义的?

ListContainer.jsx

const mapStateToProps = state => {
  return {
    list: state.list
  }
}

const mapDispatchToProps = dispatch => {
  return  {
    a: () => {}  //simple function just for testing

    //onDelete: (id) => {
    //  dispatch(actionCreators.delete(id));
    //}

  }
}

const ListContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(List);

module.exports = ListContainer;

List.jsx

module.exports = class List extends Component {

  render() {
    let list = this.props.list; //the list is on props as expected
    alert(JSON.stringify(this.props)); //function a is not on props
    ...
    return ...
  }

}

版本:“react”:“^16.0.0”,“react-redux”:“^5.0.6”,“redux”:“^3.7.2”,

【问题讨论】:

  • JSON.stringify 不显示对象中的函数。因此你看不到this.props.a 函数。只需调用this.props.a 函数进行测试。
  • 对于测试,您可以通过 null 而不是 mapDispatchToProps 到 connect 函数

标签: reactjs redux react-redux


【解决方案1】:

a: () => {}

如果你的函数没有返回任何东西,javascript 默认会返回“undefined”

【讨论】:

    【解决方案2】:

    @Prakash Sharma 是对的..您没有将函数称为道具..

    //应该派发“a”

        this.props.a();
    
        const mapStateToProps = state => {
          return {
            list: state.list
          }
        }
    
        const mapDispatchToProps = dispatch => {
          return  {
            a: () => {}  //simple function just for testing
    
            //onDelete: (id) => {
            //  dispatch(actionCreators.delete(id));
            //}
    
          }
        }
    
    const ListContainer = connect(
      mapStateToProps,
      mapDispatchToProps
    )(List);
    
    module.exports = ListContainer;
    

    【讨论】:

      猜你喜欢
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 2017-06-23
      相关资源
      最近更新 更多