React Native/Javascript-异步获取功能后无法更新视图.无效的执行顺序 [英] React Native/Javascript - Cannot update view after async fetch function. Invalid order of execution

查看:283
本文介绍了React Native/Javascript-异步获取功能后无法更新视图.无效的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面放下的代码将调用fetch()来接收一些数据,并且仅在获取数据后才会显示一个输出.但这始终无法在异步调用后更新视图.我是这个响应本机异步调用的新手,所以我希望对此有所帮助.这是代码的必要部分.

the code I have put down below will call fetch() to recieve some data and only after fetching it will display one output. But this always fails to update the view after the async call. I'm new to this react native async calls so I'd like to have some help on this. Here is the necessary parts of the code.

import React from 'react'
import {StyleSheet, View, ScrollView, Alert} from 'react-native';
import {Card, Button, Text} from 'react-native-elements';
import {TextField} from 'react-native-material-textfield';

class MyScreen extends React.Component {
    static navigationOptions = ({navigation}) => ({
        title: 'Title'
    });

    constructor(props) {
        super(props);

        const {navigation} = this.props;

        this.state = {
            loaded: false
        };
    }

    async componentWillMount() {
        let responseJson = await this.fetchData().done();
        console.log(responseJson);

        console.log('componentWillMount finished');
    }

    fetchData = async () => {
        const response = await fetch('myurl/' + GLOBAL.account_data.account.emp_number, {
            method: 'GET',
            headers: new Headers({
                'Authorization': 'Bearer ' + GLOBAL.access_token,
                'Content-Type': 'application/json'
            })
        });

        return await response.json();
    };

    render() {
        let view;
        console.log('in render');


        if (this.state.loaded) {
            view = <Text>Vikasitha</Text>
        } else {
            view = <Text>Buddhi</Text>
        }

        return (
            view
        )
    }
}

const styles = StyleSheet.create({
    card_info: {
        flex: 1,
        height: 10
    },
    card_leave: {
        flex: 2,
        height: 30
    }
});

export default MyInfoPersonalDetailsScreen;

控制台日志按以下顺序打印.

The console log are printed in the following order.

console.log('in render')
console.log(responseJson) //prints undefined
console.log('componentWillMount finished')

但是,如果await和async函数正确同步,则顺序应为

But if the await and async functions synchronize correctly, this should be in the order,

console.log(responseJson)
console.log('componentWillMount finished')
console.log('in render')

  • 是吗? (这是根据我的理解.)
  • 正确使用componentWillMount吗? (使用componentWillMount,因为它应该在呈现之前执行.与componentDidMount不同)
  • 我只想按正确的顺序获取流程.它与使用构造函数,componentWillMount和render时的执行顺序有关.不用担心未使用的变量和缺少的部分.

    I just want to get the flow in the correct order. It is about the order of execution when constructor, componentWillMount and render is used. Don't worry about the unused variables and missing parts.

    任何帮助表示赞赏!

    推荐答案

      componentDidMount() {
        // just call async function in didMount
          this.fetchData();
        }
    
        fetchData = async () => {
            const response = await fetch('myurl/' + GLOBAL.account_data.account.emp_number, {
                method: 'GET',
                headers: new Headers({
                    'Authorization': 'Bearer ' + GLOBAL.access_token,
                    'Content-Type': 'application/json'
                })
            });
    
            let result =  await response.json();
            console.log(result);
            console.log(responseJson);
            console.log('componentWillMount finished');
            // update your state here
             this.setState({result});
        };
    
    

    这篇关于React Native/Javascript-异步获取功能后无法更新视图.无效的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆