简体   繁体   English

一旦承诺履行了渲染[React Native]

[英]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. 我目前正在使用AsyncStorage( https://facebook.github.io/react-native/docs/asyncstorage )在本地加载一些数据。

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来检索该输出(在我的渲染函数中):

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

How I'm initialising the data is in my constructor in my set.State: 我如何初始化数据是在我的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. 您可以将默认值置于state中,而是在componentDidMount调用loadItems ,并在promise解析时将项设置为state。

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 <> {/* ... */} </>;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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