【问题标题】:Unhandled Rejection (TypeError): Cannot read property 'protocol' of undefined - React Hooks with axios未处理的拒绝(TypeError):无法读取未定义的属性“协议” - 使用 axios 反应钩子
【发布时间】:2021-07-25 07:33:54
【问题描述】:

我正在尝试将我的应用与 API 连接起来。它适用于类,但我尝试使用钩子。

这是错误

未处理的拒绝(TypeError):无法读取未定义的属性“协议”

这是我的代码

import React, { useState, useEffect } from "react";
import axios from "axios";

import PokemonCard from "./PokemonCard";

const Home = () => {
  const [currentState, setNewState] = useState({
    url: "https://pokeapi.co/api/v2/pokemon?limit=600",
    pokemons: null,
  });

  useEffect(() => {
    getApi();
    
    async function getApi() {
      const res = await axios.get(currentState.url);
      setNewState({ pokemons: res.data["results"] });
    }
  });

  return (
    <>
      {currentState.pokemons ? (
        <div className="pokemonCards">
          {currentState.pokemons.map((poke) => (
            <PokemonCard key={poke.name} name={poke.name} url={poke.url} />
          ))}
        </div>
      ) : (
        <h1> Loading </h1>
      )}
    </>
  );
};

【问题讨论】:

标签: reactjs axios react-hooks


【解决方案1】:

你不是说prototype吗?

无论如何,当您使用useState 时,每个实例都代表一个变量,而不是整个状态。

所以,你必须:setNewState({ url: myUrl, pokemons: myNewPokemons });

或者,甚至更好:

setNewState(prevState => {
    return {
        ...prevState,
        pokemons: myNewPokemons
    }
});

【讨论】:

    【解决方案2】:

    当我们设置状态时使用 react 的 useState 钩子时,旧状态将被清除,我们传递的新状态将是当前状态,而在基于类的组件中,状态不会覆盖旧值并会追加新值到旧值。在调用 API 之后,您没有将 URL 传递给 setNewState 函数,而只是传递了 pokemon。你需要这样做

    setNewState(prev=> {...prev , pokemons: res.data["results"]})。这将起作用

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2018-05-24
      • 2021-12-13
      • 2020-11-27
      • 2017-12-26
      • 2021-05-06
      相关资源
      最近更新 更多