【问题标题】:React async API call反应异步 API 调用
【发布时间】:2022-01-19 16:12:53
【问题描述】:

我正在尝试理解其他人的代码, 我有这个组件:

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

export default function CountriesList({ searchValue }) {
  const [data, setData] = useState([])

  //Onmount
  useEffect(() => {
    async function init() {
      //API Calls- request data from the server
      const response = await fetch('https://restcountries.com/v2/all');
      const body = await response.json();
      setData(body);
    }
    init()
  }, [])//dependencies array
  return (
    <div className="countries-container">
      {data
        .filter(country => country.name.toLowerCase().includes(searchValue.toLowerCase()))
        .map((country) => {
          const { name, flag } = country;
          return (
            <div key={name} className="country-container">
              <h3 className="title">{name}</h3>
              <img src={flag} height="100px" width="100px" alt="flag" />
            </div>
          )
        })}
    </div>
  )
}

在init()里面,程序员又调用了init(),你能解释一下为什么吗? 我试图寻找这种编程风格,但没有找到任何东西。 whiteout 这一行 API 调用不起作用。

谢谢!

【问题讨论】:

    标签: reactjs api fetch use-effect


    【解决方案1】:

    我可能弄错了,但据我所知,init 函数是在声明后立即声明和调用的。

    看看这个:https://github.com/facebook/react/issues/14326

    【讨论】:

      猜你喜欢
      • 2022-06-29
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 2017-09-16
      相关资源
      最近更新 更多