reactjs - React js:将 API 数据传递给 props 中的子组件。可以 console.log 道具但不能渲染数据
问题描述
我一直在尝试熟悉 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,
})
),
};
在此先感谢,这有点新。
解决方案
我猜你的 props.posts[0] 中的数据可能是对象,所以我会尝试使用 JSON.stringify(props.posts[0],null,2)。
推荐阅读
- node.js - Npm 安装失败。我克隆了其他 React-router 演示(具有权限功能)。但它在 npm install 上失败了
- docker - Docker 登录到 Docker Desktop for Windows 下 docker stack 中的 nexus 存储库
- remote-access - 通过本地设备远程访问服务器
- laravel - 区块链 API/Web 套接字仍然可用吗?
- css - 如何对齐复选框
- react-native - 模块 HMRClient 不是注册的可调用模块(调用设置)
- c# - C# TextBox.text 返回 null
- r - R中的周期日
- python - Python tkinter 创建新窗口时如何关闭窗口
- python - 用Python中的NaN值替换二维数组中的值