【问题标题】:Trying to put API call and getting "Actions must be plain objects. Use custom middleware for async actions."尝试进行 API 调用并获取“操作必须是普通对象。使用自定义中间件进行异步操作。”
【发布时间】:2018-09-11 15:22:39
【问题描述】:

我正在尝试使用我的 API 和 Redux 创建登录和注销页面。

目前我的类型有:LOGINLOGIN_FAILEDLOGOUT

在 reducer 中,我为每种类型创建了一个案例

看起来是这样的:

import React, { Component } from "react";
import {
  LOGIN,
  LOGIN_FAILED,
  LOGOUT
} from '../types'

 const defaultState = {
   isLoggedIn: false,
   UserName: '',
   UserEmail: '',
   UserPassword: ''
 };

  export default function reducer(state = defaultState, action) {
    switch (action.type) {
      case LOGIN:
        return Object.assign({}, state, {
            isLoggedIn: true,
            UserName: action.UserName,
            UserEmail: action.UserEmail,
            UserPassword: action.UserPassword
        });
    case LOGOUT:
        return Object.assign({}, state, {
            isLoggedIn: false,
            UserName: '',
            UserEmail: '',
            UserPassword: ''
        });
    case LOGIN_FAILED:
      return {
        UserName: '',
        UserEmail: '',
        UserPassword: '',
        isLoggedIn: false
      }
    default:
        return state;
}

这些是行动:

 import {
   LOGIN,
   LOGIN_FAILED,
   LOGOUT
 } from '../types'

 export const login = (UserName, UserEmail, UserPassword) => async (dispatch) => {
   function onSuccess(success) {
     dispatch({ type: LOGIN, payload: success })
     return success
   }
  function onError(error) {
    dispatch({ type: LOGIN_FAILED, error })
    return error
  } 
  try {
    const { UserEmail }  = this.state ;
    const { UserName }  = this.state ;
    const { UserPassword }  = this.state ;
    const res = await fetch('https://lifestormweb.000webhostapp.com/User_Login.php', {
    method: 'POST',
    headers: {
     'Accept': 'application/json',
     'Content-Type': 'application/json',
   },
   body: JSON.stringify({

     email: UserEmail,

     password: UserPassword,

     name: UserName

   })

 }).then((response) => response.json())
       .then((responseJson) => {

         // If server response message same as Data Matched
        if(responseJson === 'Data Matched')
         {
             //Then open Profile activity and send user email to profile activity.
             this.props.navigation.navigate("Profil");

         }
         else{

           Alert.alert(responseJson);
         }

       })
   const success = await res.json()
   return onSuccess(success)
 } catch (error) {
   return onError(error)
 }
};

export const logout = () => {
  return {
    type: 'LOGOUT'
  };
};

Login.js 页面:

 export class Login extends Component {
   state = {
    UserName: '',
    UserEmail: '',
    UserPassword: ''
   }

 userLogin (e) {
      this.props.onLogin(this.state.UserName, this.state.UserEmail, this.state.UserPassword);
      e.preventDefault();
  }

render() {
   return (
    <View style={styles.container}>
     <View style={styles.loginTextCont}>
    <Text style={{fontSize: 36, fontFamily: "Futura" }}>
      Willkommen zu</Text> <Text style={{fontSize: 36, fontFamily: "Futura", color:'#ff0000' }}>LifeStorm!</Text>
    <View style={{width: 10, height: 5 }} />
    </View>
    <TextInput style={styles.inputBox}
        autoCapitalize='none'
        autoCorrect={false}
        autoFocus={true}
        keyboardType='email-address'
        placeholder="Ihre Name"
        placeholderTextColor = "#ffffff"
        selectionColor="#ffffff"
        value={this.state.UserName}
        onChangeText={(text) => this.setState({ UserName: text })} />
    <TextInput style={styles.inputBox}
        autoCapitalize='none'
        autoCorrect={false}
        autoFocus={true}
        keyboardType='email-address'
        placeholder="Ihre E-Mail"
        placeholderTextColor = "#ffffff"
        selectionColor="#ffffff"
        value={this.state.UserEmail}
        onChangeText={(text) => this.setState({ UserEmail: text })} />
    <TextInput style={styles.inputBox}
        placeholder='Password'
        autoCapitalize='none'
        autoCorrect={false}
        placeholder="Ihre Passwort"
        placeholderTextColor = "#ffffff"
        selectionColor="#ffffff"
        secureTextEntry={true}
        value={this.state.UserPassword}
        onChangeText={(text) => this.setState({ UserPassword: text })} />
     <TouchableOpacity
     style={styles.button}
     onPress={(e) => this.userLogin(e)}
     >
       <Text style={styles.buttonText}>Sich einloggen</Text>
     </TouchableOpacity>
    <View style={styles.signupTextCont}>
       <Text style={styles.signupText}>
       Haben Sie kein Konto?
       </Text>
       <TouchableOpacity onPress={()=>this.props.navigation.navigate("Register")}> <Text style={styles.signupButton}> Sich anmelden</Text></TouchableOpacity>
    </View>
  </View>
  );
  }
  }

  const mapStateToProps = (state, ownProps) => {
    return {
     isLoggedIn: state.auth.isLoggedIn,
  };
  }

  const mapDispatchToProps = (dispatch) => {
   return {
    onLogin: (UserName, UserEmail, UserPassword) => { dispatch(login(UserName, UserEmail, UserPassword)); }
   }
   }

export default connect(mapStateToProps, mapDispatchToProps)(Login);

现在每次我尝试登录时都会收到以下错误:

Actions must be plain objects. Use custom middleware for async actions

我错过了什么?

【问题讨论】:

    标签: json api react-native redux react-native-ios


    【解决方案1】:

    我认为您的问题是返回您的成功/错误对象,而不仅仅是调度。你可以试试这个,看看问题是否存在:

    function onSuccess(success) {
         return dispatch({ type: LOGIN, payload: success })
         // return success  -- delete this
    }
    
    function onError(error) {
        return dispatch({ type: LOGIN_FAILED, error })
        // return error -- delete this
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 2018-01-30
      • 2020-06-17
      • 1970-01-01
      相关资源
      最近更新 更多