繁体   English   中英

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

[英]How to take the result from a fetch request and insert data into jsx?

我正在尝试处理来自 api 调用的请求并将信息插入到我的 jsx 中,但出现此错误:

“错误:对象作为 React 子级无效(发现:[object Promise])。如果您打算渲染一组子级,请改用数组。”

我可以看到它与此有关,我的 jsx 包含一个 promise,但我不明白为什么。

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>
  );
}

作为错误报告,jsx 文件无法呈现 object promise,尝试执行以下操作:

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>
  );
}

useEffect会在组件被挂载后触发,当 fetch 调用收到来自服务器的响应时, setState会将信息存储到data中,并且组件将再次呈现,但这次如果响应正确存储到data中,您应该在您的应用程序中查看 h1 列表

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>))}
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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