【发布时间】: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