【问题标题】:How to avoid null or undefined for fetch data?如何避免获取数据为空或未定义?
【发布时间】:2022-11-04 11:39:23
【问题描述】:

我有一个来自 catch(error) console.log 的错误,它是LOG [TypeError: Array.from 需要一个类似数组的对象 - 不为空或未定义]

现在我想避免 null 或 undefined我在 useState 中更新之前的函数. 那么如何避免 null 或 undefined 在这里,我的代码?

当我从 API 获取数据时,我应该在哪里使用该函数。任何人都可以帮助使用过滤器或任何函数来避免我的代码中出现 null 或 undefined 。

感谢您提前尝试!

const [item, setItem] = useState();
 
async function fD() {

        try {
            const rA = await Promise.all(devices?.map((id) => {
                const dT = fetch("https://jsonplaceholder.typicode.com/posts/1")
                    .then((response) => response.json())
                    .then((a) => {
                        return a;
                    })
  
                    .catch((error) => console.error(error));
                return dT;
            }));
            
            setItem(rA);
        }
        catch (error) {
            console.log(error);
        }
    }

【问题讨论】:

    标签: javascript react-native function filter try-catch


    【解决方案1】:

    我找到https://jsonplaceholder.typicode.com/posts/11111 回复{}

    你应该使用rA.filter(s=>s?.id ?? false)

    const [item, setItem] = useState();
    
    async function fD() {
        const rA = await Promise.all(
            (devices ?? []).map((id) => {
                const dT = fetch('https://jsonplaceholder.typicode.com/posts/1')
                    .then((response) => response.json())
                    .catch((error) => console.error(error));
                return dT;
            }),
        );
        setItem(rA.filter(s=>s?.id ?? false));
    }
    

    【讨论】:

    • 还是一样,老大!
    • @SabbirAhhmed 你关于错误日志的截图是什么? !image
    • LOG [TypeError: Array.from 需要一个类似数组的对象 - 不是 null 或未定义] 这个老板!....
    • 我需要检查您的代码错误报告堆栈
    【解决方案2】:

    在这种情况下,null 或 undefined 来自设备,因此需要确保设备值没有任何 null 或 undefine,这足以解决顶部提到的此错误。 我已经解决了问题并弄清楚了,只是觉得我应该在这里分享知识。

    【讨论】:

      猜你喜欢
      • 2020-01-02
      • 1970-01-01
      • 2021-05-26
      • 2022-11-18
      • 2022-09-26
      • 2022-10-25
      • 1970-01-01
      • 2019-01-17
      • 2021-01-12
      相关资源
      最近更新 更多