简体   繁体   中英

Objects are not valid as a React child [object Promise]

I'm new using reactjs. First case I want to get a json data from fetch url, but that json need async await to show all data. I managed to solve that problem, but now I want to append data from json to react return render. and then i get error like this Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead. . This is my code

  async function URL(url, id){
    return fetch(url+"/"+id)
    .then((response) => response.json())
    .then((responseJson) => {
        const myArrayresponse = responseJson.image.split("/");
        return "https://myurl.com/"+myArrayresponse[2]+"/"+myArrayresponse[3];
    })
    .catch((error) => {
       return "images/icon.png";
    });
  }

const posts = datas[0].map((mydata, i) => URL(mydata.uri, mydata.id).then(img => {
      return `<a href={"https://myurl.com/"+CONFIG.ADDRESS+"?a="+mydata.id} target="_blank" className="mybtn"><div className="title">{mydata.name} ({mydata.symbol} - {mydata.id})</div><img src={img} /></a>`;
      })
    );
    
return (
<ResponsiveWrapper flex={1} style={{ padding: 24 }} test>
   <s.Container flex={1} jc={"center"} ai={"center"}>
       {posts}
   </s.Container>
</ResponsiveWrapper>
)

const post is [object Promise], how to append const post to react return render without [object Promise]?

You can do it in this way:

  const [posts,setPosts]= useState([])

  async function URL(url, id){
    return fetch(url+"/"+id)
    .then((response) => response.json())
    .then((responseJson) => {
        const myArrayresponse = responseJson.image.split("/");
        return "https://myurl.com/"+myArrayresponse[2]+"/"+myArrayresponse[3];
    })
    .catch((error) => {
       return "images/icon.png";
    });
  }

  useEffect(()=>{
    async function getPosts(){
      const result = await Promise.all(datas[0].map((mydata, i) => URL(mydata.uri, mydata.id).then(img => {
        return `<a href={"https://myurl.com/"+CONFIG.ADDRESS+"?a="+mydata.id} target="_blank" className="mybtn"><div className="title">{mydata.name} ({mydata.symbol} - {mydata.id})</div><img src={img} /></a>`;
        })
      ));
      setPosts(result)
    };

    getPosts()
  },[])

return (
<ResponsiveWrapper flex={1} style={{ padding: 24 }} test>
   <s.Container flex={1} jc={"center"} ai={"center"}>
       {posts}
   </s.Container>
</ResponsiveWrapper>
)

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