【问题标题】:React Native how get data from asynchrone functionReact Native 如何从异步函数中获取数据
【发布时间】:2021-08-14 19:38:33
【问题描述】:

我尝试从异步存储函数中获取数据

 _retrieveData = async () => {
        var test = await AsyncStorage.getItem('myitem')
        return test
 }

 _generateRandomCards() {
        console.log(this._retrieveData())
 }

但是那个回报:

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}

编辑:在 Václav Ryska 的回答之后,我可以使用 setstate 更改它,但是如果我从 componentDidMount 调用 getValue 并在我的 generaterandomcards 函数中无限循环,则重新加载一次。

我的代码:

 componentDidMount() {
        this.getValue()
    }

    getValue = async () => {
        AsyncStorage.getItem('key')
        .then(data => {
            this.setState({deckDrawToday: true});
        })
    }

_generateRandomCards() {
  console.log(this.state.deckDrawToday)
  ...
  this._generateRandomCardsTrue()
  ...
  return (
            this._generateViewCards()
        )
}

_generateRandomCardsTrue() {
 ...
}

_generateViewCards() {
 ...
}

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

【问题讨论】:

    标签: react-native async-await


    【解决方案1】:

    return 不是异步函数的有效语句,您必须将回调中的值设置为变量

    this.state = {
        value: null
    }
    
    componentDidMount() {
        this.getValue();
    }
    
    getValue = async () => {
        AsyncStorage.getItem('key')
        .then(data => {
            this.setState({value: data});
            console.log(data)
        })
    }
    

    【讨论】:

    • 我已经尝试过这样,但是重新加载我的功能一次,我可以不重新加载吗?
    • 取决于你在哪里调用this.getValue()函数,如果你把它放在componentDidMount(),那么它只有在第一次渲染后才会被调用,你可以把它放在像<Button onPress={() => this.getValue()}>这样的按钮内
    • 我已经编辑了我的第一篇文章,以便用我的代码进行解释
    【解决方案2】:

    使用console.log(await this._retrieveData()),因为你的函数是异步的

    【讨论】:

    • 如果我将“异步”添加到我的函数中,我会遇到此错误:对象作为 React Child 无效
    • 使用 .then() 代替 await
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2019-04-04
    • 1970-01-01
    • 2022-01-26
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多