发布请求在react-native redux中不起作用

时间:2019-06-15 06:54:30

标签: reactjs react-native axios redux-thunk

当我调用发出网络请求的操作时,我试图使用axios调用伪造的身份验证API。 我的行动流程是

  1. 发送loginRequest
  2. 发出api请求
  3. 如果成功调度登录成功
  4. 如果失败调度loginFaliure

它首先调用loginRequest操作,然后甚至不调用任何loginFaliure操作 但是如果我检查“网络”选项卡,则请求成功 如果我提出要求,则所有动作均应按要求分派

我尝试过获取,然后使用axios

  

App.js

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import reducers from './src/store/reducers';
import LoginPage from './src/components/pages/Login';
// import './src/config/ReactotronConfig';
// import Reactotron from 'reactotron-react-native';

// To see all the requests in the chrome Dev tools in the network tab.
XMLHttpRequest = GLOBAL.originalXMLHttpRequest ? GLOBAL.originalXMLHttpRequest : GLOBAL.XMLHttpRequest;

// fetch logger
global._fetch = fetch;
global.fetch = function(uri, options, ...args) {
    return global._fetch(uri, options, ...args).then(response => {
        console.log('Fetch', { request: { uri, options, ...args }, response });
        return response;
    });
};

// redux integration
const middleware = [thunk];
if (process.env.NODE_ENV !== 'production') {
    middleware.push(createLogger());
}

const store = createStore(reducers, applyMiddleware(...middleware));

export default class App extends Component {
    render() {
        // Reactotron.log('hello from AppContainer');

        return (
            <Provider store={store}>
                <LoginPage />
            </Provider>
        );
    }
}
  

减速器

import { LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT_REQUEST } from '../constants/auth';
import { AsyncStorage } from 'react-native';

// _retrieveData = async () => {
//  try {
//      const value = await AsyncStorage.getItem('token');
//      if (value !== null) {
//          // We have data!!
//          return value;
//      }
//      return null;
//  } catch (error) {
//      // Error retrieving data
//      console.log('error fetching token', error);
//  }
// };

// const isuser =  _retrieveData();

const isuser = null;

const innitialState = {
    token: isuser ? isuser : null,
    userName: isuser ? 'ketan kulkarni' : null,
    isAuthenticated: isuser ? true : false,
    isAuthenticating: false,
    statusText: isuser ? 'Logged In' : null,
};

export const auth = (state = innitialState, action) => {
    switch (action.type) {
        case LOGIN_REQUEST:
            return { ...state, isAuthenticating: true };
        case LOGIN_SUCCESS:
            return {
                ...state,
                token: action.token,
                userName: action.userName,
                isAuthenticating: false,
                isAuthenticated: true,
                statusText: 'You have been successfully logged in',
            };
        case LOGIN_FAILURE:
            return {
                ...state,
                token: null,
                userName: null,
                isAuthenticated: false,
                isAuthenticating: false,
                statusText: `Authentication Error ${action.status} ${action.statusText}`,
            };
        case LOGOUT_REQUEST:
            return {
                ...state,
                isAuthenticated: false,
                token: null,
                userName: null,
                statusText: 'You have been successfully logged out.',
            };
        default:
            return state;
    }
};
  

动作

import { LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT_REQUEST } from '../constants/auth';
import axios from 'axios';

export const loginRequest = () => ({
    type: LOGIN_REQUEST,
});

export const loginSuccess = title => {
    return {
        type: LOGIN_SUCCESS,
        token: title,
        username: 'ketan',
    };
};

export const loginFailure = error => {
    return {
        type: LOGIN_FAILURE,
        status: 'error.response.status',
        statusText: 'login failed',
    };
};

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

export const loginUser = (email, password) => async dispatch => {
    dispatch(loginRequest());
    try {
        console.log('requesting');
        const res = await axios.get(`https://reqres.in/api/login`, { email, password });
        console.log('request done', res);
        //decode token then
        dispatch(loginSuccess('data'));
    } catch (error) {
        console.log({ error });
        dispatch(loginFailure(error));
    }
    // setTimeout(() => {
    //  if (1) dispatch(loginSuccess('data'));
    // }, 2000);

    // axios
    //  .post(`https://reqres.in/api/login`, { email, password })
    //  .then(() => dispatch(loginSuccess('data')))
    //  .catch(err => dispatch(loginFailure(err)));

    // fetch('https://reqres.in/api/login', {
    //     method: 'GET',
    //     headers: {
    //         Accept: 'application/json',
    //         'Content-Type': 'application/json',
    //     },
    //     body: JSON.stringify({
    //         email,
    //         password,
    //     }),
    // })
    //     .then(() => dispatch(loginSuccess('data')))
    //     .catch(err => dispatch(loginFailure(err)));
};
  

loginPage

import React, { Component } from 'react';
import { Button, StyleSheet, View } from 'react-native';
import { loginUser } from '../../store/actions/auth';
import { connect } from 'react-redux';

class LoginPage extends Component {
    _onPressButton = async () => {
        await this.props.dispatch(loginUser('eve.holt@reqres.in', 'cityslicka'));
        console.log('here');
    };

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.buttonContainer}>
                    <Button onPress={this._onPressButton} title="Press Me" />
                </View>
            </View>
        );
    }
}

export default connect(null)(LoginPage);

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    buttonContainer: {
        margin: 20,
    },
    alternativeLayoutButtonContainer: {
        margin: 20,
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
});
  

预期输出-

第一个补丁登录请求 如果api请求成功,则调度登录成功 如果api请求失败,则调度loginFailure

  

实际输出-

发出请求时 分派loginRequest 则不会有任何动作被派发

如果请求获取 一切正常

1 个答案:

答案 0 :(得分:0)

我在App.js中添加的用于检查“网络”标签中的网络请求的代码导致了错误

// To see all the requests in the chrome Dev tools in the network tab.
// XMLHttpRequest = GLOBAL.originalXMLHttpRequest ? GLOBAL.originalXMLHttpRequest : GLOBAL.XMLHttpRequest;

// // fetch logger
// global._fetch = fetch;
// global.fetch = function(uri, options, ...args) {
//  return global._fetch(uri, options, ...args).then(response => {
//      console.log('Fetch', { request: { uri, options, ...args }, response });
//      return response;
//  });
// };