【发布时间】:2019-07-18 23:53:02
【问题描述】:
在实际对象加载之前,使用 Axios 和 useEffect 获取数据会导致 null。
不幸的是,在实际对象不为空之前,我无法使用对象解构。
我不得不使用钩子来检查一个对象是否为空。
例如,我想创建多个函数并将我的代码拆分为单独的函数以提高可读性。
这是我的 HTTP 请求 Hook:
import { useState, useEffect } from 'react';
import axios from 'axios';
export const useHttp = (url, dependencies) => {
const [isLoading, setIsLoading] = useState(false);
const [fetchedData, setFetchedData] = useState(null);
useEffect(() => {
setIsLoading(true);
axios
.get(url)
.then(response => {
setIsLoading(false);
setFetchedData(response.data);
})
.catch(error => {
console.error('Oops!', error);
setIsLoading(false);
});
}, dependencies);
return [isLoading, fetchedData];
};
后面是我的页面组件:
import React from 'react';
import { PAGE_ABOUT, API_URL } from 'constants/import';
import Header from './sections/Header';
import Main from './sections/Main';
import Aside from './sections/Aside';
import { useHttp } from 'hooks/http';
const About = () => {
const [isLoading, about] = useHttp(PAGE_ABOUT, []);
if (!isLoading && about) {
return (
<section className="about">
<div className="row">
<Header
featuredImage={API_URL + about.page_featured_image.path}
authorImage={API_URL + about.page_author_image.path}
authorImageMeta={about.page_author_image.meta.title}
title={about.about_title}
subtitle={about.about_subtitle}
/>
<Main
title={about.page_title}
content={about.page_content}
/>
<Aside
title={about.about_title}
content={about.about_content}
/>
</div>
</section>
);
}
};
export default React.memo(About);
实际问题是我无法在对象实际返回之前嵌套函数。
有没有办法在不检查的情况下获取数据?或者更清洁的解决方案会有所帮助。
我想使用多个组件来拆分代码。
任何意见或建议将不胜感激。
【问题讨论】:
-
我真的不确定代码的哪一部分给您带来了问题?你能再解释一下吗?
-
我和 Zeljko 在同一条船上,我不确定实际的问题/问题是什么。
-
我有这个“if (!isLoading && about) {”我无法在这个 IF 语句之外添加箭头函数,因为它首先返回 null 导致我的应用程序返回未定义。我想使用对象解构而不是使用 about.title,about.section 我只想使用“title”和“section”。而且我想将完整的代码拆分为多个内联组件,但我不能在 if 语句之外执行此操作。有没有办法只在没有检查的情况下加载数据?
-
你能创建一个 stackblitz/codesandbox 演示来展示这个问题吗?
标签: reactjs