【问题标题】:Fetching data from api promise in react API [closed]从反应 API 中的 api promise 获取数据 [关闭]
【发布时间】:2021-11-08 15:33:37
【问题描述】:

我使用 package.json 中的特定代理从 Company API 获取数据。

这是我的代码:

const [products, setProducts] = useState({
        loading: false,
        data: null,
        error: false,
    });

    const apiLink = 'https://example.com/api/checkout/products/';

    useEffect(() => {
        setProducts({
            loading: true,
            data: null,
            error: false,
        });

        fetch(apiLink, {
                method: 'POST',
                body: JSON.stringify({
                    "categories": [
                        "13", "14", "4", "8"
                    ]
                })
            })
            .then(response => {
                response.json().then(data => console.log(data.products))
            })
    }, [apiLink])

但是当我使用 console.log() 时,它在控制台中显示的数据是这样的:

Promise {<pending>}
   [[Prototype]]: Promise
   [[PromiseState]]: "fulfilled"
   [[PromiseResult]]: Object

并且在 [[PromiseResult]] 里面有我需要处理的信息。喜欢:产品

如何访问此产品并将其循环到我的页面中。请问我需要帮助。

因为当我访问这样的产品时:

console.log(products.data.products)

我在控制台中未定义。

【问题讨论】:

    标签: javascript reactjs api


    【解决方案1】:

    MDN: Uploading JSON data 中所述,从 API 接收数据后,您应该在单独的 .then 进程中处理每个操作。

    fetch(apiLink, {
      method: 'POST',
      body: JSON.stringify({
        "categories": [
           "13", "14", "4", "8"
        ]
      })
    })
    .then(response => response.json())
    .then(data => console.log(data.products))
    
    

    【讨论】:

    • 兄弟,但我需要在 setProducts() ` .then(response => response.json()) .then(data => setProducts({ loading: false, data: data. products, error: false }) ) ` 当我像这样映射它时` content = products.data.products.map(product => { console.log(product) }) ` 我得到这样的错误 TypeError: Cannot read properties未定义(阅读“地图”)
    • 映射时不需要指定“data.products”。应该像这样映射 --- content = products.map(product => console.log(product)
    • 好的,现在问题有所不同了。在.then(data =&gt; console.log(data.products)) 行中,结果是什么?它记录什么?它是一个对象数组吗?
    • 你能打印 json() 响应只知道你有什么数据形状吗then(response =&gt;console.log( response.json()))
    【解决方案2】:

    只有在 fetch() 方法中才需要 promise,因为它是一个延迟计算,之后您可以使用任何方法来处理您的数据

    fetch(apiLink, {
      method: 'POST',
      body: JSON.stringify({
        "categories": [
           "13", "14", "4", "8"
        ]
      })
    })
    .then(response => response.json())
    .catch(x=>console.log(x)).map(x=>console.log(x.products))

    你可以在https://learnjsx.com/category/2/posts/es6-promise了解更多关于 Promise 的信息

    【讨论】:

      【解决方案3】:

      你可以在useEffect中使用async/await

      useEffect(() => {
        const init = async () => {
          setProducts({
            loading: true,
            data: null,
            error: false,
          });
      
          try {
            const response = await fetch(apiLink, {
              method: "POST",
              body: JSON.stringify({
                categories: ["13", "14", "4", "8"],
              }),
            });
            response = await response.json();
            // set your state after this
          } catch (e) {
            console.error(e);
          }
        };
      
        init();
      }, [apiLink]);
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-09
        • 2021-07-31
        • 2019-02-23
        • 1970-01-01
        • 2014-01-15
        • 1970-01-01
        • 1970-01-01
        • 2017-02-20
        相关资源
        最近更新 更多