【发布时间】:2020-02-28 02:06:47
【问题描述】:
我已经花了几个小时试图在 ReactNative useEffect 钩子中调用 API。有时当我重新启动我的应用程序时,该值已解决。但大多数时候,我有一个Unhandled promise rejection。我用谷歌搜索并尝试了各种方法。我尝试使用.then 等。我就是想不通。
import React, { useState, useContext, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, FlatList } from 'react-native';
import { EvilIcons } from '@expo/vector-icons';
import jsonServer from '../api/jsonServer';
const ShowScreen = ({ navigation }) => {
const id = navigation.getParam('id');
const [post, setPost] = useState([]);
const getBlog = async () => {
const result = await jsonServer.get(`http://0.0.0.0/blog/docroot/jsonapi/node/article/${id}`);
return result;
}
useEffect(() => {
async function setToState() {
const val = await getBlog();
setPost(val);
}
setToState();
},[]);
return (
<View>
<Text>Here { console.log(post) }</Text>
</View>
);
};
ShowScreen.navigationOptions = ({ navigation }) => {
return {
headerRight: (
<TouchableOpacity
onPress={() =>
navigation.navigate('Edit', { id: navigation.getParam('id') })
}
>
<EvilIcons name="pencil" size={35} />
</TouchableOpacity>
)
};
};
const styles = StyleSheet.create({});
export default ShowScreen;
【问题讨论】:
-
jsonServer 正在返回一个承诺。你在处理吗?
-
尝试简化您的代码以对其进行调试,将调用 jsonServer.get 移动到 setToState 并将主体包装在 try catch 中并将 id 添加到 useEffect 的依赖数组中以避免重新渲染中的额外调用
标签: react-native react-hooks es6-promise use-effect