Javascript 如何从获取请求中获取结果并将数据插入jsx?

Javascript 如何从获取请求中获取结果并将数据插入jsx?,javascript,reactjs,promise,fetch,jsx,Javascript,Reactjs,Promise,Fetch,Jsx,我试图处理来自api调用的请求,并将信息插入我的jsx,但出现以下错误: 错误:对象作为React子对象无效(找到:[object Promise])。如果要呈现子对象集合,请改用数组 我可以看出这与我的jsx包含一个承诺有关,但我不明白为什么 import React from "react"; export default function Card_Container() { return ( <div> {fetch("

我试图处理来自api调用的请求,并将信息插入我的jsx,但出现以下错误:

错误:对象作为React子对象无效(找到:[object Promise])。如果要呈现子对象集合,请改用数组

我可以看出这与我的jsx包含一个承诺有关,但我不明白为什么

import React from "react";

export default function Card_Container() {
  return (
    <div>
      {fetch("http://localhost:1337/posts")
        .then((res) => res.json())
        .then((data) => {
          data.map((post) => {
            return <h1>{post.blogtitle}</h1>;
          });
        })}
    </div>
  );
}
从“React”导入React;
导出默认功能卡\u容器(){
返回(
{fetch(“http://localhost:1337/posts")
.然后((res)=>res.json())
。然后((数据)=>{
data.map((post)=>{
返回{post.blogtile};
});
})}
);
}

作为错误报告,jsx文件无法呈现对象承诺,请尝试执行以下操作:

import React, { useEffect, useState } from "react";

export default function Card_Container() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("http://localhost:1337/posts")
      .then((res) => res.json())
      .then((res) => {
        setData(res);
      });
  }, []);

  return (
    <div>
      {data.map((post) => {
        return <h1>{post.blogtitle}</h1>;
      })}
    </div>
  );
}
import React,{useffect,useState}来自“React”;
导出默认功能卡\u容器(){
const[data,setData]=useState([]);
useffect(()=>{
取回(“http://localhost:1337/posts")
.然后((res)=>res.json())
。然后((res)=>{
setData(res);
});
}, []);
返回(
{data.map((post)=>{
返回{post.blogtile};
})}
);
}

组件装入后会触发
useffect
,当fetch调用从服务器接收到响应时,
setState
将信息存储到
数据中,组件将再次呈现,但是这一次,如果响应正确地存储在
数据中
您应该会在应用程序中看到一个h1列表

我建议您查看React文档中的示例:查看我的库,它完全是为这种情况构建的,并利用React提供的相对较新的服务作为其实验并发模式的一部分。该库也支持,因此您不必启用并发模式即可使用它。谢谢!这解决了我的问题。谢谢你的回答。
Import React from "react";

export default function Card_Container() {
  return (
    <div>
      { fetch("http://localhost:1337/posts")
         .then((res) => res.json())
         .then((data) => {
          data.map((post => {
            <h1>{post.blogtitle}</h1>
          ))})};
    </div>
  );
}
componentDidMount(){
            console.log(">>>>> componentDidMount...");
            url= 'http://localhost:1337/posts';
            fetch(url)
            .then((response) => response.json())
            .then((responseJson) => {
              console.log(JSON.stringify(responseJson));
              this.setState({result:responseJson});
              return responseJson;
            })
            .catch((error) => {
              console.error(error);
            });
          }

render() {
              return( 
                <div>
                    {this.state.result.map(post => (
                         <h1>{post.blogtitle}</h1></div>))}