React-Native setState不异步更新状态

时间:2017-06-20 22:28:25

标签: react-native setstate

import React from 'react';
import {View}  from 'react-native';
import Button from 'react-native-button';

const gData  = [{counter: 0}];

export default class App extends React.Component {

  constructor(props)
  {
    super(props);
    this.state = {data: {}};
    console.log("Constructor: ", this.state.data);
  }
  _handlePress()
  {
    console.log("Pressed Button")
    gData[0].counter += 1;
    console.log("Before setState: ", gData);
    this.setState({data: gData}, console.log("After setState: ", this.state.data));
  }

  render() {
    return (
      <View style={{flex:1, justifyContent: 'center',}}>
        <Button
          onPress={() => this._handlePress()}>
          Press Me!
        </Button>
      </View>
    );
  }
}

您好, 我有一个简单的反应本机应用程序代码,它在屏幕上创建一个按钮,按下它应该更新对象内的计数器并将对象存储在状态中。但是,当我运行应用程序并按下按钮时,我会在日志中看到它:

11:19:43 PM:在为x86_64构建的Android SDK上运行应用程序

11:19:43 PM:构造函数:{}

11:23:20 PM:按下按钮

11:23:20 PM:在setState之前:[{&#34; counter&#34;:1}]

11:23:20 PM:在setState之后:{}

因此由于某种原因,状态未更新。有谁知道那是什么情况?

1 个答案:

答案 0 :(得分:0)

非常确定如果你调用console.log就会立即调用它,而不是一旦状态完成更新,请尝试将其放入匿名函数中:

    this.setState({data: gData}, () => console.log("After setState: ", this.state.data));