我一直在努力熟悉 React。我有兩個組件。API 呼叫是在父組件上進行的,我正在嘗試將資料傳遞給子組件。
這是我的父組件:
export default function LandingPage(props) {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get("https://jsonplaceholder.typicode.com/posts").then((response) => {
setPosts(response.data);
});
}, []);
const classes = useStyles();
const { ...rest } = props;
return (
<div>
<div className={classNames(classes.main, classes.mainRaised)}>
<div className={classes.container}>
{/* HERE IS THE CHILD COMPONENT BELOW */}
<ProductSection posts={posts} />
</div>
</div>
<Footer />
</div>
);
}
這是我的子組件:
export default function ProductSection(props) {
const classes = useStyles();
return (
<div className={classes.section}>
{/* HERE IS THE CONSOLE LOG */}
{console.log(props.posts[0])}
{/* HERE IS THE RENDER */}
<Typography>{props.posts[0]}</Typography>
</div>
);
}
ProductSection.propTypes = {
posts: PropTypes.arrayOf(
PropTypes.shape({
userId: PropTypes.number,
id: PropTypes.number,
title: PropTypes.string,
body: PropTypes.string,
})
),
};
提前致謝,對這個有點陌生。
uj5u.com熱心網友回復:
我想可能你在 props.posts[0] 中的資料是物件,所以我會嘗試使用 JSON.stringify(props.posts[0],null,2)。
uj5u.com熱心網友回復:
資料是物件,如果共享排版組件會更清楚。雖然我嘗試在沒有排版的情況下解決它,并且在為不存在的 postData 添加條件后它的作業,因為資料將被獲取并等待承諾提供服務。這是作業。
App.js -> 父級
ProductSection.js -> 子級
請參閱此沙箱,它將幫助您撰寫代碼。請參閱此沙箱以獲得更清晰的資訊:
關聯
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/321701.html
