【问题标题】:How to take the result from a fetch request and insert data into jsx?如何从 fetch 请求中获取结果并将数据插入 jsx?
【发布时间】:2021-06-20 09:43:48
【问题描述】:

我正在尝试操作来自 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>
  );
}

【问题讨论】:

标签: javascript reactjs promise fetch jsx


【解决方案1】:

如报错,jsx文件无法渲染对象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 列表

【讨论】:

    【解决方案2】:
    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>
      );
    }
    

    问题不在于逻辑,而在于语法。 =&gt; 已经作为回报,因此无需添加另一个。

    最佳实践:

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

    【讨论】:

      猜你喜欢
      • 2020-03-05
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多