React Native异步执行

时间:2018-04-21 12:33:10

标签: javascript react-native

我想执行一些异步函数来从db中获取一些数据,而不会冻结UI。
这是我写的代码

export default class CustomComponent extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     value:0
   };
 }

  componentWillMount() {
    this.fetchData().then(result => { this.setState(value:result);});
  }

  async fetchData() {    
    var appState = await someMethod()
    return appState;
  }

  someMethod() {
   return new Promise(resolve => {
         resolve(queryFromDB())
        });
  }

  queryFromDB() {
     // Returns a value fetched from Realm
     let events = this.realm.objects("Event");
     return events.length;
   }

  render() {
   return (
     <Text> {this.state.value} </Text> 
   );
  }
}

问题是它确实在主线程上执行,冻结了应用程序。
错误是什么?

1 个答案:

答案 0 :(得分:0)

好像你的代码有语法错误。您已在构造函数中编写了所有代码。试试这个。

export default class CustomComponent extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     value:0
   };
 }

  componentWillMount() {
    this.fetchData().then(result => { this.setState(value:result);});
  }

  async fetchData() {    
    var appState = await someMethod()
    return appState;
  }

  someMethod() {
   return new Promise(resolve => {
         resolve(queryFromDB())
        });
  }

  queryFromDB() {
     // Returns a value fetched from Realm
     let events = this.realm.objects("Event");
     return events.length;
   }

  render() {
   return (
     <Text> {this.state.value} </Text> 
   );
  }
}