【问题标题】:Set State Inside Async Function in React Native(Expo)在 React Native(Expo)中设置异步函数内部的状态
【发布时间】:2019-01-24 12:00:41
【问题描述】:

我正在使用 Expo of React Native,我需要将 API Fetch 响应保存到状态。

我的代码是这样的:

onPress={async () => {

                  if (this.camera) {
                    const options = { quality:0, base64: true};
                    let photo = await this.camera.takePictureAsync(options);
                      setTimeout(()=>{     
                      fetch('https://c7pl8gkrj6.execute-api.ap-southeast-1.amazonaws.com/prod/rekog', {
                        method: 'POST',
                        headers: {
                          Accept: 'application/json',
                          'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                          base64: photo['base64'],
                        }),
                      }).then((responseJson) => {  
                        this.setState({
                            response:responseJson
                            })
                        })
                        .catch((error) => {
                          console.error(error);
                        });
                        this.setState({captured:true})
                        }, 3000)

                  }
                }}

我想将响应存储在名为“响应”的状态变量中。但是当我想显示保存在状态中的响应时,它将呈现为空。

if(this.state.captured){
        console.log(this.state.response)
        return(
          <View style={styles.container}>
        <SectionList
          sections={[
            {title: 'response1', data: [this.state.response]}
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
          renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
          keyExtractor={(item, index) => index}
        />
      </View>
        );
         }else{
           ...

在这里,console.log(this.state.response) 显示 {} 即空值。是不是异步函数没有显示保存在状态中的值的问题。

【问题讨论】:

    标签: react-native expo


    【解决方案1】:

    当然不是,只要您的 API 确实返回结果,但您应该这样做。

    onPress={async () => {
    
                  if (this.camera) {
                    const options = { quality:0, base64: true};
                    let photo = await this.camera.takePictureAsync(options);
                      setTimeout(()=>{     
                      await fetch('https://c7pl8gkrj6.execute-api.ap-southeast-1.amazonaws.com/prod/rekog', {
                        method: 'POST',
                        headers: {
                          Accept: 'application/json',
                          'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                          base64: photo['base64'],
                        }),
                      }).then(function(response) {
                          return response.json()
                        }).then((responseJson) => {  
                        this.setState({
                            response:responseJson
                            })
                        })
                        .catch((error) => {
                          console.error(error);
                        });
                        this.setState({captured:true})
                        }, 3000)
    
                  }
                }}
    

    你错过了几行。

    【讨论】:

      【解决方案2】:

      您需要首先提取响应,因此您必须在 setState 之前编写一个,然后承诺如下所示,其中 reponse.json() 提取实际响应并将其传递给 responseJson。谢谢,希望对你有用。

         .then(reponse => response.json())
         .then((responseJson) => {  
             this.setState({
                 response:responseJson
             })
          })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-22
        • 2018-08-02
        • 2021-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-22
        相关资源
        最近更新 更多