使用React Native和useEffect获取



试图调用API以获取一些数据并将其存储在我的组件状态中。我使用具有[]依赖关系的useEffect只激发一次。setEntries行导致Expo在iOS上死机。如果我对此进行评论,我可以登录并看到API正在返回我所期望的结果。我想知道调用setEntries是否会引发某种无限循环,但当我登录到控制台时,我没有看到这种情况发生。

我还测试过将isLoadingentriesisError添加到依赖数组中,但没有成功。

以下相关代码:

import React, { useEffect, useState } from 'react';
import { SafeAreaView, ScrollView, Text } from 'react-native';
import { globalStyles } from '../../../styles';
import Card from '../../shared/components/card';
import { Entry } from '../../shared/models/Entry';
import { REQUEST } from '../../shared/services/networking';
export const EntryList = () => {
const [entries, setEntries] = useState([]);
const [isError, setIsError] = useState(false);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetch(url)
.then((result) => {
setIsLoading(false);
if (result.ok) {
return result.json();
} else {
throw new Error(result.status.toString());
}
})
.then((entries) => {
if (entries) {
setEntries(entries.data.sort((a: Entry, b: Entry) => Date.parse(b.createdAt) - Date.parse(a.createdAt)));
}
})
.catch((e) => {
console.error(e);
setIsError(e);
});
}, []);
return (
<SafeAreaView style={globalStyles.container}>
<ScrollView showsVerticalScrollIndicator={false}>
{isError && <Text>Sorry, we encountered an error.</Text>}
{isLoading && <Text>Loading...</Text>}
{entries && !isLoading ? (
entries.map((entry, i) => <Card entry={entry} key={`entry-${i}`} />)
) : (
<Text>No entries found. Tell us about your day :)</Text>
)}
</ScrollView>
</SafeAreaView>
);
};

编辑:一些额外的细节使这个问题更加复杂。当我在MacBook上运行此代码时,Expo可以正常工作。当我在Linux桌面(Elementary OS(上运行相同的代码时,我会得到上面描述的行为。正因为如此,我在这里打开了一个关于世博会的问题:https://github.com/expo/expo/issues/11352

我认为问题可能是因为您的state中有相同的名称entries,而.then((entries) => {...})中有请求响应。尝试更改响应中的名称,如响应或类似的内容

.then((response) => {
if (response) {
setEntries(response.data.sort((a: Entry, b: Entry) => Date.parse(b.createdAt) - Date.parse(a.createdAt)));
}
})

最新更新