如何在 Expo 的渲染方法中调用异步方法?

时间:2021-04-15 15:17:52

标签: react-native expo

我将数据保存到 AsyncStorage。现在我想在单独的屏幕中显示来自 AsyncStorage 的所有数据。 方法 getData 是异步方法。它从 AsyncStorage 读取。 我使用这样的代码

import React from "react";

class List extends React.Component {
  state = { list: null };

  async componentDidMount() {
    const list = await getData("List");
    console.log('LIST: ' + JSON.stringify(list));
    this.setState({ list });
  }

  render() {
    const { list } = this.state;
    console.log('state: ' + JSON.stringify(list));

    if(list || list.length <= 0)
         return (<View><Text>Empty.</Text></View>);

    return (
                <View>
                    { list.map(item => (
                        <Text tabLabel={item}>{item}</Text>
                    ))}
                </View>
        );
   }
}

当我运行该代码时,我收到 2 条控制台消息: 状态: [] 和 列表:[{item1}, {item2}...]

这意味着 componentDidMount 在 render 方法之后触发,这就是 UI 为空的原因。

我该如何改变这一点。我需要从 AsyncStorage 读取数据并将其显示在 UI 中。

谢谢。

1 个答案:

答案 0 :(得分:0)

componentDidMount 正如标题所说的那样是为了在渲染之后运行。要实现您想要做的事情,您可以使用 componentWillMount

import React from 'react';

class List extends React.Component {
  state = { list: null };

  componentWillMount() {
    const loadData = async () => {
      const list = await getData('List');
      console.log('LIST: ' + JSON.stringify(list));
      this.setState({ list });
    };

    loadData();
  }

  render() {
    const { list } = this.state;
    console.log('state: ' + JSON.stringify(list));

    if (list || list.length <= 0)
      return (
        <View>
          <Text>Empty.</Text>
        </View>
      );

    return (
      <View>
        {list.map((item) => (
          <Text tabLabel={item}>{item}</Text>
        ))}
      </View>
    );
  }
}