如何使用分派(react-redux)到类组件中 [英] How to use a dispatch (react-redux) into class Component

查看:45
本文介绍了如何使用分派(react-redux)到类组件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码

class LoginPage 扩展组件 {使成为() {返回 (<div><文本输入/><br/><文本输入/><br/><按钮 onClick={() =>{const 调度员 = useDispatch();调度员(singIn())}}>唱歌</按钮>

);}}

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

解决方案

对于类组件,需要使用 react-redux 中的 connect 方法.使用 connect 方法并传递 mapDispatchToProps 函数,如下所示.

import { connect } from 'react-redux';类 LoginPage 扩展组件 {使成为() {返回 (<div><文本输入/><br/><文本输入/><br/><Button onClick={() =>{this.props.singIn()}}>唱歌</按钮>

);}}const mapDispatchToProps = (调度) =>{返回 {登录: () =>调度(登录())}};导出默认连接(空,mapDispatchToProps)(登录页面)

通读文档了解更多信息.https://react-redux.js.org/api/connect

My code

class LoginPage extends Component {

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

I guess that I am using a hooks in a class component, but what can I use instead of useDispacth to my LoginPage?

解决方案

For class components, you need to use connect method from react-redux. Use connect method and pass mapDispatchToProps function as shown below.

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)

Read thru the doc for more info. https://react-redux.js.org/api/connect

这篇关于如何使用分派(react-redux)到类组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆