React Native提取在另一个提取回调中不起作用

时间:2018-11-26 04:58:49

标签: react-native fetch-api

如果我从POINT 1调用api函数,则api方法中的fetch方法效果很好。当我注释掉并在POINT 2的addAccount()内部调用方法时不起作用。没有例外,没有拒绝,没有对Reactotron的请求,即使我找不到通过Charles Proxy的请求。有什么区别,我必须知道如何解决?

我尝试了RN 0.55.2和0.57.5

// Auth.js typical react native component

import * as api from '../actions/api';

class Auth extends Component {

    // first triggered function
    loginAccount(){
        // api.addAccount();  // POINT 1 - this line works well if I uncomment
        fetch('https://domain-a.com/login/',{
                method: 'POST',
                credentials: "same-origin",
                headers: {
                    'accept-language': 'en-US;q=1',
                    'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
                },
                body: encodeURIComponent(bodyParameters)
            }).then((response) => {
                console.log(response);
                return response.json()
            }).then(({ status, invalid_credentials }) => {
                if(status == "ok"){
                    CookieManager.get('https://domain-a.com')
                        .then((cookies) => {
                            this.fetchAccountData(cookies);
                        })
            })

    }

    fetchAccountData(cookies){
        fetch('https://domain-a.com/'+cookies.user_id+'/info/',{
            method: 'GET',
            headers: {
                'cookie': cookies
                }
        }).then((response) => {
            return response.json();
        })
        .then(({ user, status }) => {
            api.addAccount(); // POINT 2 - this line doesn't work
        });
    }
}


// api.js 
// I repleaced fetch code with document example just to be clearify

export const addAccount = () => {
    console.log("fetch begin"); // always works
    fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
        console.log(responseJson);  // won't works from point 2
    })
    .catch((error) =>{
        console.error(error); // never runs
    });
}

1 个答案:

答案 0 :(得分:0)

您的addAccount()函数中的第一个.then语句似乎缺少return语句。没有正确的'return response.json()'语句,responseJson将是不确定的。还添加了括号,以实现更好的语义格式。

getSideInputsMap()

}