【问题标题】:I need help (Api calls in React Js Hooks) Why is this nort working?我需要帮助(React Js Hooks 中的 Api 调用)为什么这不起作用?
【发布时间】:2022-06-10 16:37:59
【问题描述】:

我需要帮助(React Js Hooks 中的 Api 调用)为什么这个 nort 工作? 我需要调用该 API 中的值

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

function Customers() {
    const [customers, setCustomers] = useState(null);

    useEffect(() => {
    fetch('https://reactstarter-app.herokuapp.com/api/customers')  **API CALLS**
        .then(res => res.json())
        .then(customers => setCustomers(customers))
}, [])

return (
    <div>
        <h2>Customers</h2>
        <ul>
            {customers.map((customer) => {
                return <li key={customer.id}>{customer.firstName} {customer.lastName}</li>
            })}
        </ul>
    </div>
);
}

export default Customers;

【问题讨论】:

  • 您有一个名为“customers”的常量,但在获取时,您将 res.json() 用作:.then(customers =&gt; setCustomers(customers))。你应该叫它别的名字,比如:.then(data =&gt; setCustomers(data))
  • 感谢您的回复,但我不太明白。你能修改代码并粘贴吗
  • @SagarKattel 我认为问题在于 API 被 CORS 阻止。尝试先捕获错误
  • @SagarKattel 试试这个 API,而不是 https://cors-anywhere.herokuapp.com/https://reactstarter-app.herokuapp.com/api/customers
  • 谢谢@MochamadFaishalAmir

标签: javascript reactjs api react-hooks use-effect


【解决方案1】:

也许这不是一个解决方案,但我不能粘贴代码来评论,所以我必须发布一个答案:

function Customers() {
    // this is where you declare the "customers" const
    const [customers, setCustomers] = useState(null);

    useEffect(() => {
    fetch('https://reactstarter-app.herokuapp.com/api/customers')  **API CALLS**
        .then(res => res.json())
        // this is where you should change the "customers" to "data"
        // because of the variable name conflict
        .then(data => setCustomers(data))
}, [])

【讨论】:

【解决方案2】:

看起来您正在尝试通过 null 状态进行映射并且可能出现错误,请使用条件渲染来避免错误并在 api 请求后渲染客户:

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

function Customers() {
    const [customers, setCustomers] = useState(null);

    useEffect(() => {
    fetch('https://reactstarter-app.herokuapp.com/api/customers')  **API CALLS**
        .then(res => res.json())
        .then(customers => setCustomers(customers))
}, [])

return (
    <div>
        <h2>Customers</h2>
        {!customers ? <h2>Loading customers...</h2> :
         <ul>
            {customers.map((customer) => {
                return <li key={customer.id}>{customer.firstName} {customer.lastName}</li>
            })}
        </ul>}
    </div>
);
}

export default Customers;
猜你喜欢
  • 1970-01-01
  • 2014-10-01
  • 2021-03-15
  • 2021-03-03
  • 2020-11-04
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多