首页 > 解决方案 > 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,
    })
  ),
};



在此先感谢,这有点新。

标签: reactjsapi

解决方案


我猜你的 props.posts[0] 中的数据可能是对象,所以我会尝试使用 JSON.stringify(props.posts[0],null,2)。


推荐阅读