【问题标题】:Can you make render() method in React Native async?你可以在 React Native 异步中创建 render() 方法吗?
【发布时间】:2019-02-06 01:30:35
【问题描述】:

我有一个 React Native 组件,它需要从异步存储中获取一个对象才能进行渲染。像这样。

class Class1 extends Component {
  async render() {
    let data = AsyncStorage.getItem('data');
    return (
      <View>
        {data}
      </View>
    )
  }
}

我让我的 render() 方法成为异步函数的原因是我可以等待 AsyncStorage.getItem() 方法的返回,这样组件就不会尝试返回直到 'data ' 对象已从异步存储返回。但是,当我使用“async render()”时,我会得到“Invariant Violation: Objects are not valid as a React child”。

有什么建议吗?

【问题讨论】:

    标签: react-native asynchronous


    【解决方案1】:

    不需要,你想要这样的条件渲染。

    _retrieveData = async () => {
      try {
        const value = await AsyncStorage.getItem('data');
        if (value !== null) {
          // We have data!!
          return (
              <View>{value}</View>
          );
        }
      } catch (error) {
        // Error retrieving data
      }
    };
    

    然后在你的渲染函数中,调用它。

    render() {
      return (
        {this._retrieveData()}
      )
    }
    

    【讨论】:

    • 感谢您的快速回复!但是,由于您使用的是“let data = ...”而不是“let data = await ...”,所以“if(data)”不会总是在 getItem() 返回之前被调用,因此总是返回 false?
    • 我刚刚更新了它以使用来自react-native AsyncStorage documentation 的示例。我倾向于使用 react-native-simple-store 而不是 AsyncStorage,因为我发现它更容易使用。
    • @gkeenley 你能发布你的解决方法吗?我也在尝试这样做,但无法与上面的示例一起使用
    猜你喜欢
    • 2016-06-07
    • 2022-08-11
    • 2019-09-30
    • 2017-02-14
    • 1970-01-01
    • 2023-03-28
    • 2023-04-06
    • 1970-01-01
    • 2016-07-27
    相关资源
    最近更新 更多