React Native / Javascript-异步获取功能后无法更新视图。无效的执行顺序

时间:2018-08-20 08:47:21

标签: javascript reactjs typescript react-native async-await

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

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;

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

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

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

console.log(responseJson)
console.log('componentWillMount finished')
console.log('in render')
  • 是吗? (这是我的理解。)
  • 正确使用componentWillMount吗? (使用componentWillMount,因为它应该在呈现之前执行。与componentDidMount不同)

我只想按正确的顺序获取流程。这与使用构造函数,componentWillMount和render时的执行顺序有关。不用担心未使用的变量和缺少的部分。

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

  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});
    };