为什么不能在有状态组件中使用UseDispatch?

问题描述 投票:0回答:1

为什么我们不能在有状态组件中使用Hook UseDispatch?

import { useDispatch } from "react-redux";
import { submitData } from "../state/actions";

class FormComponent extends Component {
  constructor(props) {
    super(props);
     this.state = {
       fields: {},
       errors: {}
     };
  }

 submitForm = e => {
    e.preventDefault();
    if (this.validateForm()) {
      useDispatch(submitData(this.state.fields));
    }
  };
}

}

我为具有字段的简单表单创建了有状态组件,并且还跟踪了state.fields中的所有数据,我想使用Hook方法UseDispatch。为什么我不能在其中使用Hook?

reactjs react-redux
1个回答
0
投票

[使用有状态组件(从React.Component或PureComponent继承的类时,不能使用UseDispatch钩子或任何钩子。

正如Dupocas所说,挂钩仅在function components中可用。

相反,您需要使用connect中的connect实用程序将组件连接到redux存储:

react-redux

import { connect } from 'react-redux'; import { submitData } from "../state/actions"; class FormComponent extends Component { constructor(props) { super(props); this.state = { fields: {}, errors: {} }; } submitForm = e => { const { dispatchSubmitData } = this.props; e.preventDefault(); if (this.validateForm()) { dispatchSubmitData(this.state.fields); } }; } } const mapStateToProps = null; function mapDispatchToProps(dispatch) { return { dispatchSubmitData: (...args) => dispatch(submitData(...args)) }; } export connect(mapStateToProps, mapDispatchToProps)(FormComponent);

© www.soinside.com 2019 - 2024. All rights reserved.