【问题标题】:React fetch request from external API after card click卡片点击后响应来自外部 API 的获取请求
【发布时间】:2020-04-06 20:42:12
【问题描述】:

我有一个小问题。 点击卡片后,我的应用会获取请求。 但我有一些麻烦。我的 fetch 请求每次都在做,但它必须在点击后才做。 所以我的 fetch 请求如下所示:

  useEffect(() => {
    let endpointForPokemonDetails = `${API_URL}${index}`;
    fetchPokemonDetails(endpointForPokemonDetails);
  });

  const fetchPokemonDetails = (endpointForPokemonDetails) => {
    fetch(endpointForPokemonDetails)
      .then((result) => result.json())
      .then((result) => {
        setPokemon([Pokemon, result]);
      }, setLoading(false))
      .catch((error) => console.log("Error:", error));
  };

在我点击卡片之前,console.log 中有一些错误:

你知道怎么解决吗?

【问题讨论】:

    标签: javascript reactjs rest get fetch


    【解决方案1】:

    在您的按钮(或任何其他 HTML 元素)上使用 onClick 属性:

    <button type="button" onClick={() => fetchPokemonDetails(index)}>
    Fetch pokemon
    </button>
    

    同时更改 fetchPokemonDetails 以接受索引参数:

     const fetchPokemonDetails = (index) => {
        fetch(`${API_URL}${index}`)......
    

    useEffect 是一个用于触发副作用的 React 钩子。 见https://reactjs.org/docs/hooks-reference.html#useeffect

    【讨论】:

      【解决方案2】:

      通过使用 useEffect,你告诉 React 你的组件需要在渲染之后做一些事情。 React 会记住你传递的函数(我们将其称为“效果”),并在执行 DOM 更新后调用它

      所以你得到错误的原因是因为你使用了useEffect。这将在使用 index = undefined 进行渲染后调用 API

      您可以删除 useEffect 方法并在 onClickHandler 上调用 fetchPokemonDetails

      【讨论】:

        【解决方案3】:

        你只能使用点击事件,所以你只能在点击后使用该功能,你不应该使用useEffect。 useEffect 有副作用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-07
          相关资源
          最近更新 更多