首页 > 解决方案 > mapDispatchToProps 函数不起作用 React Redux

问题描述

有带有登录组件的 react-redux。我试图通过 mapDispatchToProps 将 acitons 与组件的道具链接,但得到了错误:

×
TypeError: this.props.login is not a function

这是代码:

import React from 'react'
import {connect} from 'react-redux'
import * as userActions  from '../actions/UserActions'

export class Login extends React.Component{
    constructor(props) {
        super(props)
        this.login = this.login.bind(this)
    }

    login () {
        console.log(this)
        this.props.login(this.username,this.password)
    }

    render(){
        return <div>
            <div class="login-box">
                <form>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Имя пользователя</label>
                        <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Username" ref = {(input)=>{this.username = input}} />
                    </div>
                    <div class="form-group">
                        <label for="exampleInputPassword1">Пароль</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" ref = {(input)=>{this.password = input}} />
                    </div>
                    <button class="btn btn-primary" onClick= {this.login} >Войти </button>
                </form>
                </div>
        </div>
    }
}

const mapDispatchToProps = dispatch => {
    return {
        login:(username,password) => {
            dispatch(userActions.login(username,password))
        }
    }
}

export default connect(null,mapDispatchToProps)(Login)

PS:如果有帮助,我正在使用 react-redux-router

标签: javascriptreactjsreduxflux

解决方案


推荐阅读