简体   繁体   中英

ReactJs: How to pass api data to components?

I call api in Home.js file with componentdidmount in class component and i want to render this data in child components with functional components.when i call api in every each child component, its work but when i try to call with props coming only empty array by console.log please help.

 import React,{Component} from 'react' import '../styles/home.css' import axios from 'axios'; import Teaser from './Teaser' import Second from './Second' import Opening from './Opening' import Menu from './Menu' export default class Home extends React.Component { state = { posts: [] } componentDidMount() { axios.get("https://graph.instagram.com/me/media?fields=id,caption,media_url,permalink,username&access_token=IG").then(res => { const posts = res.data.data; this.setState({ posts }); }) } render() { return ( <> <Teaser/> <Second/> <Opening/> <Menu posts = {this.state.posts}/> </> ) } }

 import React from 'react' import axios from 'axios'; function Menu(props) { const {posts} = props; console.log(props); return ( <> {posts && posts.map( (post) => post.caption.includes('#apegustosa_menu') && post.children.data.map((x) => ( <div className="menu_item" key={x.id}> <img className="menu_img" src={x.media_url} alt="image" /> </div> )), )} </> ) } export default Menu

Here you go:

  return (
    <>
      {
        posts && posts.map(post => (
          post.caption.includes("#apegustosa_menu") && post.children.data.map(x => {
            return <img src={x.media_url} alt="img"></img>
          })
        ))
      }
    </>
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM