简体   繁体   中英

Rendering once the promise fulfilled [ React Native ]

I'm currently using AsyncStorage ( https://facebook.github.io/react-native/docs/asyncstorage ) to load in some data locally.

Currently I am retrieving the data successfully which initially gets returned as a promise which fulfils and the data is returned.

The issue I'm having right now is that I want to render this data on my screen HOWEVER, it is rendering when the promise isn't quite fulfilled yet.

In my logs I can see the following output:

Item Returned:  Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}
Item Returned:  Array [
  Object {
    "ItemID": "1234",
    "ItemName": "Big Fluffy Bear",
  },
]

That output is being retrieved by calling console.log only once (In my render function):

console.log("Item Returned: ", this.state.itemsStoredLocally);

How I'm initialising the data is in my constructor in my set.State:

this.state = {
  itemsStoredLocally: loadItems().then(
    data => this.setState({
      itemsStoredLocally: data
    }))
};

What's currently happening is the page is rendering before the promise is resolved. How can I ensure that my page waits to load AFTER the promise is resolved?

A promise is always resolved asynchronously, so you cannot resolve it and set it in the component's initial state.

You can put a default value in state and instead call loadItems in componentDidMount and set the items in state when the promise resolves.

Example

class MyComponent extends React.Component {
  state = {
    itemsStoredLocally: []
  };

  componentDidMount() {
    loadItems().then(data =>
      this.setState({
        itemsStoredLocally: data
      })
    );
  }

  render() {
    const { itemsStoredLocally } = this.state;

    if (itemsStoredLocally.length === 0) {
      return null;
    }
    return <> {/* ... */} </>;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM