将对象数组传递给 ReactJS 中的子组件,但第一个返回它是未定义的并破坏代码



我正在为我的品牌制作个人博客,帖子部分的工作原理是使用 API 从基本JSON获取数据,现在用 mirageJS 模拟,并使用useEffectuseState钩子,我正在使用array.map()函数为屏幕上显示的<PostComponent />设置数据。问题是:

  • 如果我想将数组设置为子组件中的状态钩子,我会收到一个错误,因为第一次返回它是"未定义的",尽管第二次返回它是正确的 JSON。

帖子页面.js//家长//

import React, {useState, useEffect} from 'react';
import PostComponent from './Post';
import { Spinner } from 'react-bootstrap';
import '../MenuBar/MenuBar.css';
import '../../assets/Global.css'

function HomePage() {
const [post, setPost] = useState([]); //array of objects of the post's content
const [isLoaded, setIsLoaded] = useState(false); //If it's false, display 'loading' icon

//Fetching data from the API
useEffect(() => {

fetch(`/api/posts`)
.then((res) => res.json())
.then((data) => {
setPost(data.posts);
setIsLoaded(true);
})
.catch(err => {
throw err;
});      
}, []);
console.log(post); //checking the return
function SpinnerIcon(){ //'Loading' icon
return(
<div className="menu-bar">
<div className="menu-aligner">
<div className="spinner-box">
<Spinner 
className="load-animation" 
animation="border" 
variant="info" />
</div>
</div>
</div>
)
}
function PostsList() {//Posts 
return(
<div className="menu-bar">
<div className="menu-aligner">
{
post.map(item => (
<PostComponent infos={item} key={item.id} />
))
}
</div>
</div>
)
}
function HandleChange(props){
if(props.props === false){
return <SpinnerIcon />
} else {
return <PostsList />
}
}

return (
<HandleChange props={isLoaded}/>
);
}
export default HomePage;

邮政.js//儿童//

import { Row, Col } from 'react-bootstrap';
import square from '../../assets/img/square.png';
function PostComponent(infos) {
console.log(infos.infos); //checking the received data
return(
<article className="article-box">
<Row>
<Col xs={3}>
<img className="article-img" src={square} alt="imagem" />
</Col>
<Col xs={7} className="inside-text" >
<h3>{infos.infos.name}</h3>
{<span dangerouslySetInnerHTML={{__html:[infos.infos.descrip]}}></span>}
<br/>
<Row>
<Col xs={10}>
<button>Ler Mais</button>
</Col>
<Col xs={1} className="date-post">
<small>{infos.infos.date}</small>
</Col>
</Row> 
</Col>
</Row> 
</article>
)
}
export default PostComponent;

我想知道是否有第一次返回的可能性不是未定义的,或者在这种情况下有什么好的做法。

这是你的问题infos.infos.name

您有两种方法可以解决此问题

1. 你可以做infos && infos.infos.name.仅当信息不是虚假值时,才会显示。

阿拉伯数字。 您可以使用infos?.infos?.name

由于您正在映射post那么您的帖子是一个数组,因此您不应该遇到此问题。 如果你有一个空数组,它将映射任何内容。如果您的数组中有项目,那么它将映射到您的PostComponent

您为我们遗漏了一些代码,以便能够正确理解这一点。

最新更新