我这里有一个非常奇怪的问题。我已经创建了基于页面的组件“关于”。我正在使用useEffect和Axios来获取我的API数据。这是可行的,但是,当我在控制台上记录我的数据时,使用效果会在渲染时返回2倍的空数组,然后是对象,该对象也会运行两次。
现在,我创建了一个加载器,以查看数据是否在数组内,然后,我想显示数据。这样做会得到错误: TypeError:当我删除 page__header 前的支票时,无法读取未定义的属性'path'。
怎么来?
我的组件
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { PAGE_ABOUT, API_URL } from 'constants/import';
import ReactHtmlParser from 'react-html-parser';
const About = () => {
const [pageContent, setPageContent] = useState([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
const result = await axios(PAGE_ABOUT);
setPageContent(result.data);
setIsLoading(false);
};
fetchData();
}, []);
const {
page_title,
page_content,
page_author_image,
page_featured_image,
} = pageContent;
console.log(pageContent);
return (
!isLoading && (
<section className="about">
<div className="page">
<div className="row">
<div className="col-xs-12">
<div
className="page__header"
style={{
backgroundImage: `url(${API_URL +
page_featured_image.path})`,
}}
/>
</div>
<div className="col-xs-12 col-sm-8">
<div className="about__info">
<h3>{page_title}</h3>
{ReactHtmlParser(page_content)}
</div>
</div>
<div className="col-xs-12 col-sm-4">
<aside className="about__sidebar">
{page_author_image &&
page_author_image.path && (
<img
src={
API_URL + page_author_image.path
}
alt={page_author_image.meta.title}
className="about__image"
/>
)}
<h3 className="about__title">
Marina & Nino
</h3>
<span className="about__subtitle">
Fragrance lover
</span>
<p className="about__content">
This is a custom author box widget where you
can display your photo, social media links
and some information about yourself.
</p>
</aside>
</div>
</div>
</div>
</section>
)
);
};
export default React.memo(About);