【问题标题】:"Actions may not have an undefined "type"“动作可能没有未定义的“类型”
【发布时间】:2019-07-19 06:03:22
【问题描述】:

我收到此错误“操作可能没有未定义的“类型”属性。您是否拼错了常量?”,当我提交登录值(用户名、密码)以检查 redux 是否正常工作时。我为此尝试了不同的解决方案,但仍然出现错误,请帮助!

authActions.js

import axios from 'axios';
import {REGISTER_SUCCESS,REGISTER_FAIL,LOGIN_SUCCESS,LOGIN_FAIL,
    LOGOUT_SUCCESS,USER_LOADING,USER_LOADED,AUTH_ERROR} from './actionType';


export const register = ({username, name, email, password}) => {

    return (dispatch, getState) => {

        const config = {
            headers : {
                'Content-type' : 'Application/json'
            }
        }

        const body = JSON.stringify({
            username,
            name,
            email,
            password
        })

        axios.post('http://localhost:5000/users/register', body , config )
        .then(res => dispatch({
            type : REGISTER_SUCCESS,
            payload : res.data 
        }))
        .catch(err => {
            dispatch(returnErrors(err.response.data, err.response.status, REGISTER_FAIL));
            dispatch({
                type : REGISTER_FAIL
            })
        });
    };
};

export const login = ({username, password}) => {
    return (dispatch, getState) => {

        const config = {
            headers : {
                'Content-type' : 'Application/json'
            }
        }

        console.log(username);

        const body = JSON.stringify({
            username,
            password
        })

        axios.post('http://localhost:5000/users/login', body , config)
        .then(res => setTimeout(() => {
            dispatch({
                type : LOGIN_SUCCESS,
                payload : res.data
            })
        },2000));
    };
}

export const logout = () => {
    return {
        type : LOGOUT_SUCCESS
    }
}

export const loadUser = () => {
    return (dispatch, getState) => {
        dispatch({
            type: USER_LOADING,
        });

        axios.get('http://localhost:5000/users/auth' , tokenConfig(getState))
        .then(res => dispatch({
            type: USER_LOADED,
            payload : res.data
        }))
        .catch(err => {
            dispatch(returnErrors(err.response.data.message, err.response.status));
            dispatch({
                type : AUTH_ERROR
            });
        })
    }
}


//
export const tokenConfig = (getState) => {

    const token = getState().auth.token;

    const config = {
        headers : {
            'content-type' : 'Application/json',
        }
    }

    if(token) {
        config.headers['auth'] = token;
    }

    return config;
} 

actionType.js

export const REGISTER_SUCCESS = 'REGISTER_SUCCESS';
export const REGISTER_FAIL = 'REGISTER_FAIL';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_FAIL = 'LOGIN_FAIL';
export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS';
export const USER_LOADING = 'USER_LOADING';
export const USER_LOADED = 'USER_LOADED';
export const AUTH_ERROR = 'AUTH_ERROR';

LoginForm.js

import React, {Component} from 'react';
import {
    //StyleSheet,
    View,
    Text,
    TextInput,
    Button    
  } from 'react-native';
  import {reduxForm,Field} from 'redux-form';
  import {connect} from 'react-redux';
  import {login} from './authActions';

  const validate = values =>{
      const errors = {};
      if(!values.username){
          errors.username="Please fill the username"
          return errors;

      }
      if(!values.password){
        errors.password="Please fill the password"
        return errors;

    }
  }

  const myFields = ({label,meta:{error,touched}, input:{onChange}}) =>{
      return(
          <View>
            <Text>{label}</Text>
            <TextInput style={{borderWidth:1,width:300,marginBottom:10}}            
            onChangeText={onChange}/>
            {touched && (error && (<Text style={{color:'red'}}>{error}</Text>))}
          </View>
      );
  }

  const passFields = ({label,meta:{error,touched}, input:{onChange}}) =>{
    return(
        <View>
          <Text>{label}</Text>
          <TextInput style={{borderWidth:1,width:300,marginBottom:10}}
          secureTextEntry={true}        
          onChangeText={onChange}/>
          {touched && (error && (<Text style={{color:'red'}}>{error}</Text>))}
        </View>
    );
}


  const submitbtn = (values,login) =>{
      alert(`here are the values ${JSON.stringify(values)}`);
      login(values);

  }

  const myLoginForm = props => {

      const {handleSubmit} = props;
      const {login} = props;
      return(


        <View>
            <Field
            name="username"           
            component={myFields}
            label="UserName"/>

            <Field
            name="password"           
            component={passFields}
            label="Password"
           />

            <Button title="Submit"
            onPress={handleSubmit(submitbtn,login)}/>

        </View>
      );
  }

  const LoginForm = reduxForm({
      form:'loginform',
      validate
  })(myLoginForm);

  const mapStateToProps =(state) =>({
    isAuthenticated: state.auth.isAuthenticated
  });

  export default connect(mapStateToProps,{login})(LoginForm);

【问题讨论】:

    标签: react-native react-redux


    【解决方案1】:

    如下编辑您的 actionType.js 文件

    export const REGISTER_SUCCESS = 'REGISTER_SUCCESS';
    export const REGISTER_FAIL = 'REGISTER_FAIL';
    export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
    export const LOGIN_FAIL = 'LOGIN_FAIL';
    export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS';
    export const USER_LOADING = 'USER_LOADING';
    export const USER_LOADED = 'USER_LOADED';
    export const AUTH_ERROR = 'AUTH_ERROR';
    
    export default {
        REGISTER_SUCCESS,
        REGISTER_FAIL,
        LOGIN_SUCCESS,
        LOGIN_FAIL,
        LOGOUT_SUCCESS,
        USER_LOADING,
        USER_LOADED,
        AUTH_ERROR
    }
    

    这是因为它没有从动作文件中获取动作常量。您可以按照上面的代码更改 actionType.js。

    其他解决方案是您不需要更改 actionType.js。您需要按以下方式更改 actionType.js 的用法

    import * as ActionType from './actionType.js'
    

    如下使用这个变量

    ... 
    axios.post('http://localhost:5000/users/register', body , config )
        .then(res => dispatch({
            type : ActionType.REGISTER_SUCCESS,
            payload : res.data 
        }))
    ...
    

    【讨论】:

    • 尝试但仍然错误是“操作可能没有未定义的“类型”属性。您是否拼错了一个常量?”如果您需要任何其他文件,请告诉我..
    • @UmairYaqub 你用过其他解决方案吗?另请检查 actionType.js 的路径,它与 authActions.js 文件位于同一文件夹中。
    • 是的,我只是尝试了这两种解决方案,但对我不起作用。我还检查了 actionType 的路径。请帮忙!
    猜你喜欢
    • 2018-02-04
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多