为什么当我单击按钮后,在获取Prmise和this.setState之后才打印控制台日志

时间:2019-03-27 14:14:53

标签: javascript react-native promise

我有一个touchableOpacity区域,里面有图像。当用户单击图像时,我想将touchableOpacity的不透明度设置为0.2,然后执行获取,其结果将为0或1。如果为0,则将图像更改为黑白图像,否则为彩色图像。但是我无法做到这一点。找不到我单击touchableOpacity区域时,console.log在控制台中打印其值但未设置state.opacity的原因。

import React, { Component } from 'react';
import {Image, TouchableOpacity, View, Text, StyleSheet, StatusBar } from 'react-native';
import styles from './Estilos';

export default class LightsContainer extends Component {
constructor() {
super();

  this.state = { opacity: 0.9 };
}

onPress = () => {

    fetch("http://192.168.0.161/switch.php?port=1")
        .then(response => response.text()) 
        .then((dataStr) => {

        console.log(dataStr);     

        if (dataStr == 1){

            this.setState({opacity: 0.9});
            console.log("si");

        } else {

            this.setState({opacity: 0.2});
            console.log("no");

        }
    });     

    console.log(this.state);
}

render() {
return (
 <View style={{flex: 1}}>
  <View style={{flex: 1, backgroundColor: 'steelblue', justifyContent: 'center', alignItems: 'center'}}  >
        <TouchableOpacity style={{opacity: this.state.opacity}} onPress={this.onPress.bind(this)} >
            <Image source={require('./bulb-512.png')}  style={{width: 150, height: 150, top:-40}} />
      </TouchableOpacity>
        <TouchableOpacity style={styles.button}  >
            <Image source={require('./bulb-512.png')}  style={{width: 150, height: 150, top:-10}} />
      </TouchableOpacity>
        <TouchableOpacity style={styles.button}  >
            <Image source={require('./bulb-512.png')}  style={{width: 150, height: 150, top:20}} />
      </TouchableOpacity>
    </View>
</View>
);
}
}

1 个答案:

答案 0 :(得分:1)

由于JavaScript是一种同步语言,因此控制台日志几乎都会立即发生。

在返回取回之前(数据仍在传入时),console.log(this.state)将已经发生,因此onPress的最后一行将记录初始状态。还请记住React's setState method itself is asynchronous!,因此si完成后,nosetState的日志可能不会出现。

要解决此问题,您可能需要研究async/await syntax,等待承诺解决,这将使您的异步代码“同步”运行