【发布时间】:2020-11-20 17:11:12
【问题描述】:
我在 useEffect 函数中实现了 fetch 并收到以下错误: An Effect must not return anything besides a function, which is used for cleanup
这是相同的代码sn-p:
const Tab1 = () => {
const [arr, updateArr] = useState([]);
const [loading, setLoading] = useState(true);
const myFunc = txt => {
console.log("Hello");
console.log(txt);
}
useEffect(() => {
return fetch('http://testapi')
.then((response) => response.json())
.then((json) => updateArr(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<View style={styles.container}>
<FlatList
data={arr.categories}
renderItem={itemData => (
<TouchableOpacity
onPress={() => this.myFunc(itemData.item.cno)}
>
<View>
<Text>{itemData.item.cno}</Text>
<Text>{itemData.item.name}</Text>
</View>
</TouchableOpacity>
)}
keyExtractor={(item, index) => item.cno}
/>
</View>
)
}`
【问题讨论】:
-
错误信息是正确的。您不应返回
fetch调用,而应直接调用它。所以:useEffect(() => { fetch(...)... }, []); -
在您的代码中,
useEffect的函数返回一个Promise...只需remove的return 语句,警告就会消失。如果useEffect的函数有返回值,那应该是清理函数,而不是Promise -
请不要将图像用于堆栈跟踪,如果可能,请始终将其作为文本粘贴到此处。
标签: reactjs react-native