【问题标题】:How to use a dispatch (react-redux) into class Component如何在类组件中使用调度(react-redux)
【发布时间】:2020-04-08 04:57:39
【问题描述】:

我的代码

class LoginPage extends Component {

  render() {
    return (
        <div>
          <TextInput/>
          <br/>
          <TextInput/>
          <br/>
          <Button onClick={() => {
            const dispatcher = useDispatch();
            dispatcher(singIn())
          }}>SING IN</Button>
        </div>
    );
  }
}

我猜我在类组件中使用了钩子,但是我可以使用什么来代替 useDispacth 到我的 LoginPage?

【问题讨论】:

  • 感谢您的帮助

标签: javascript reactjs redux react-redux


【解决方案1】:

对于类组件,您需要使用来自react-reduxconnect 方法。使用 connect 方法并传递mapDispatchToProps 函数,如下所示。

import { connect } from 'react-redux';
class LoginPage extends Component {

    render() {
        return (
            <div>
                <TextInput/>
                <br/>
                <TextInput/>
                <br/>
                <Button onClick={() => {
                    this.props.singIn()
                }}>SING IN</Button>
            </div>
        );
    }
}



const mapDispatchToProps = (dispatch) => {
    return {
        signIn: () => dispatch(signIn())
    }
};
export default connect(null, mapDispatchToProps)(LoginPage)

阅读文档以获取更多信息。 https://react-redux.js.org/api/connect

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2019-11-29
    • 1970-01-01
    • 2021-07-02
    • 2021-01-28
    • 2022-12-09
    • 1970-01-01
    • 2018-05-05
    • 2019-10-23
    相关资源
    最近更新 更多