代码之家  ›  专栏  ›  技术社区  ›  levye

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

  •  0
  • levye  · 技术社区  · 6 年前

    在addAccount()中

    我试过使用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 回复  |  直到 6 年前
        1
  •  0
  •   ck706    6 年前

    看起来addAccount()函数中的第一个.then语句缺少返回语句。如果没有正确的“return response.json()”语句,responseJson将是未定义的。还添加了括号以更好地设置语义格式。

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