【问题标题】:post request not working in react-native redux发布请求在 react-native redux 中不起作用
【发布时间】:2019-10-29 16:14:47
【问题描述】:

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

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

它首先调用loginRequest 操作,然后它不调用任何操作,甚至loginFaliure 但如果我检查网络选项卡请求成功 如果我提出 get 请求,所有操作都按应有的方式调度

我试过 fetch,然后用 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)));
};

登录页面

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 请求成功 dispatch loginSuccessful 如果 api 请求失败 dispatch loginFailure

实际输出 -

发出post请求时 调度登录请求 然后没有任何动作被调度

如果有获取请求 一切正常

【问题讨论】:

    标签: reactjs react-native axios redux-thunk


    【解决方案1】:

    我在 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;
    //  });
    // };
    

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 2021-08-12
      • 1970-01-01
      • 2018-08-02
      • 2018-08-31
      • 2022-10-21
      • 1970-01-01
      • 2017-12-23
      • 2022-06-22
      相关资源
      最近更新 更多