【问题标题】:after bind MapDispatchtoProps Can't use this.props绑定 MapDispatchtoProps 后不能使用 this.props
【发布时间】:2016-09-27 06:11:23
【问题描述】:

我试图找出我的代码有什么问题。有人可以帮我找出问题所在。我使用 webstorm 进行文本编辑,它在

中显示“未解析变量”

this.props.loginUser(value);

有什么相关的吗?

这是我的代码:

import React, { Component } from 'react'
import {reduxForm,  Field} from 'redux-form';
import { loginUser } from '../actions/index';
import { Stores }   from '../Stores';
import {connect} from 'react-redux';

const validate = values => {
    const errors = {};
    if (!values.email) {
        errors.email = 'Required'
    } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
        errors.email = 'Invalid email address'
    }
    if (!values.password) {
        errors.password = 'Required'
    }
    return errors
};

const renderField = ({ input, label, type, meta: { touched, error } }) => (
    <div>
        <label>{label}</label>
        <div>
            <input {...input} placeholder={label} type={type} className="form-control"/>
            {touched && error && <span className="alert alert-danger">{error}</span>}
        </div>
    </div>
);

function submit(value){
    console.log(value);
    this.props.loginUser(value); //didn't work
    // Stores.dispatch(loginUser({email,password})); //this method work
}

class LoginV6 extends Component{

    render() {
        const {handleSubmit, pristine, reset, submitting} = this.props;

        return (
            <div className="row">
                <div className="col-md-6">

                    <form onSubmit={handleSubmit(submit)}>
                        <div className="form-group">
                            <Field
                                name="email"
                                type="text"
                                component={renderField}
                                label="Email"
                            />
                        </div>

                        <div className="form-group">
                            <Field
                                name="password"
                                type="password"
                                component={renderField}
                                label="Password"
                            />
                        </div>

                        <div>
                            <button type="submit" className="btn btn-primary" disabled={pristine||submitting}>
                                Login
                            </button>

                            <button type="button" className="btn btn-primary" disabled={pristine || submitting}
                                    onClick={reset}>
                                Clear Values
                            </button>
                        </div>
                    </form>

                </div>
            </div>
        )
    }
}

 const mapDispatchToProps = (dispatch) => {
     return {
         loginUser() {
             dispatch({loginUser(value));
         }
     }
};

function mapStateToProps(state) {
    return {
        errorMessage: state.auth.error,
        authenticated:state.auth.authenticated
    }
}

LoginV6 =  reduxForm({
    form:'LoginV6',
    validate
})(LoginV6);

export default LoginV6 = connect(mapStateToProps, mapDispatchToProps)(LoginV6);

这是我的操作代码:

import axios from 'axios';
import jwtdecode from 'jwt-decode';
import {browserHistory} from 'react-router';
import {
    AUTH_USER,
    AUTH_ERROR,
    USER_INFO_SUCCESS,
    USER_INFO,
    LOGOUT_USER,
    GET_TABPANEL,
    GET_SETUP_TABTITLES,
} from './types';

const ROOT_URL = 'http://localhost:8000';

// User and Auth actions
// 
export function loginUser({email,password}){
    return function(dispatch){
        axios.post(`${ROOT_URL}/api/auth/login`,{email,password})
            .then(response => {
                dispatch({type: AUTH_USER,
                    payload:response.data.token
                });
                localStorage.setItem('laravel_user_token',response.data.token);
                console.log('Login Success');
                browserHistory.push("/");
            }).catch(()=>{
            dispatch(authError("Empty Required Field"));
        });
    }
}

如果我使用 Stores.dispatch(loginUser(value)); 它可以工作。

【问题讨论】:

  • 你在控制台看到什么错误
  • @Aatif Bandey:什么都没发生。
  • 你在父组件中定义了 prop loginUser 吗?
  • @Aatif Bandey : 类 LoginV6 是父组件。
  • 我没用过redux 我用过flux 但我认为你没有定义prop loginUser 这给你带来了问题

标签: reactjs redux redux-form


【解决方案1】:

像这样更改您的代码:

class LoginV6 extends Component{
    constructor(){
        this.submit = this.submit.bind(this); //Because ES6 is not auto bind
    }
    submit(value){
        //...your code
        this.props.loginUser(value); //it will work
        // or "loginUser" is an action
        this.props.dispatch(loginUser(value)); //see the new function mapDispatchToProps
    }
    render(){
        //...your code 
    }
}
// ....
// instead map a new object, we map dispatch directly 
// with this function, we avoid duplicated/confused about actions in case you have many actions
const mapDispatchToProps = (dispatch) => {
    return {
        dispatch
    }
};

【讨论】:

  • 出现错误。我将构造函数更改为这个:constructor(props){ super(props); this.submit = this.submit.bind(this); //Because ES6 is not auto bind } 但我在
    上遇到另一个错误,它在控制台上说:“LoginV6.js:54 Uncaught ReferenceError: submit is not defined”跨度>
  • 你可以试试 "onSubmit={handleSubmit(this.submit)}" 。因为函数 submit 现在属于 LoginV6 类。此外,您的代码有点复杂,“handleSubmit”和“loginUser”是操作。 “handleSubmit”应该写在LoginV6类里面,和函数“submit”含义相同
  • @Nguyễn Nhân:我已经尝试过了。这是工作。非常感谢你。
【解决方案2】:

我已经通过将我的代码更改为这个来解决这个问题:

class LoginV6 extends Component{

    submit = (data) => {
        console.log(data);
        this.props.loginUser(data);
    }

    render() {
        const {handleSubmit, pristine, reset, submitting} = this.props;

        return (
            <div className="row">
                <div className="col-md-6">

                    <form onSubmit={handleSubmit(this.submit)}>

..............................the rest of code..............................................

    const mapDispatchToProps = (dispatch) => {
        return {
            loginUser: (data) => {
                dispatch(loginUser(data))
            }
        }
    }

    function mapStateToProps(state) {
        return {
            errorMessage: state.auth.error,
            authenticated:state.auth.authenticated
        }
    }

    LoginV6 =  reduxForm({
        form:'LoginV6',
        validate
    })(LoginV6);

    export default LoginV6 = connect(mapStateToProps, mapDispatchToProps)(LoginV6);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2018-02-27
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多