【问题标题】:Fetch using React Native and useEffect使用 React Native 和 useEffect 获取
【发布时间】:2021-03-23 23:53:36
【问题描述】:

尝试调用 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)上运行相同的代码时,我得到了上述行为。正因为如此,我在这里打开了一个关于 Expo 的问题:https://github.com/expo/expo/issues/11352

【问题讨论】:

  • 可能是您的排序功能崩溃了?
  • 你遇到了什么错误?
  • 就是这样,没有错误只是 Expo 冻结在我身上并最终崩溃。不知道我做错了什么......
  • 排序函数不会因为日志而崩溃,如果我注释掉setEntries,则会显示一个排序数组。

标签: reactjs react-native react-hooks fetch use-effect


【解决方案1】:

我认为问题可能是因为您在 state 中具有相同的名称 entries 并在 .then((entries) =&gt; {...}) 中请求响应。尝试在您的回复中更改名称,例如回复或类似的内容

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

【讨论】:

  • 出色的收获!非常感谢!!
  • 真的很奇怪,这在我的 Macbook 上开发时工作正常。然后,我继续在我的 Linux 计算机上进行开发,发现与我原来的错误相同,尽管您进行了更改。
猜你喜欢
  • 2021-09-22
  • 2020-03-07
  • 2021-10-07
  • 2021-12-28
  • 2021-08-16
  • 2020-09-15
  • 2021-03-16
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多