React TypeError: Cannot read property 'length' of undefined

React TypeError: Cannot read property 'length' of undefined

我正在构建小型 React 应用程序。主要任务是使用 PokeApi 创建关于口袋妖怪的应用程序。当我点击 pokeCard 时,我的侧边栏必须显示有关 pokemon 的主要信息。所以,我想显示口袋妖怪的数量。我们怎么知道,所有数字都以 # 开头。但是在PokeApi中,小精灵的编号不是以#开头的,也不包含任何0。例如,Charmander的编号是#004,但在PokeApi中,Id是4。 所以,我用逻辑运算符创建了条件。请看:

  {(pokemon.id.length === 1 && <span>#00{pokemon.id}</span>) ||
      (pokemon.id.length === 2 && <span>#0{pokemon.id}</span>) ||
      (pokemon.id.length === 3 && <span>#{pokemon.id}</span>)}

我希望我创建的是正确的。但是,在我的屏幕上我看到 TypeError: Cannot read property 'length' of undefined 。我想,这是因为,在我点击之前,pokemon.id 是未定义的。我尝试创建 typeof(pokemon.id) == "undefined" && <span>loading</span> ,但它不起作用。

这是代码,我是如何设置口袋妖怪的。

const [SelectedPokemon, setSelectedPokemon] = useState([]);

 const fetchPokemonDetails = (pokemonId) => {
    fetch(`${API_URL}${pokemonId}`)
      .then((result) => result.json())
      .then((result) => {
        setSelectedPokemon(result);
      }, setLoadingForSelectedPokemon(false))
      .catch((error) => console.log("Error:", error));
  };

你能帮我解决一下吗?

请确保数据调用正常。 这是因为您的数据还没有准备好。

代码应该是这样的

{(pokemon && pokemon.id.length === 1 && <span>#00{pokemon.id} 
 </span>) ||
  (pokemon && pokemon.id.length === 2 && <span>#0{pokemon.id} 
 </span>) ||
  ( pokemon && pokemon.id.length === 3 && <span>#{pokemon.id} 
 </span>)}

您正试图在 属性 定义之前访问它。您可以尝试使用下面的代码片段吗?

{pokemon.id !== undefined ? 
(pokemon.id.length === 1 && <span>#00{pokemon.id}</span>) ||
      (pokemon.id.length === 2 && <span>#0{pokemon.id}</span>) ||
      (pokemon.id.length === 3 && <span>#{pokemon.id}</span>)
: null}

主要问题是您试图在 pokemon.id 实际定义之前使用它。如果喜欢,我会建议将您的陈述放在另一个中:

{ pokemon.id ? this.handleId(pokemon.id) : "" }

哪里

handleId = (id) => {
  let holder = "#000";
  let arr = holder.split("");
  id.split("").reverse().map((e, i) => arr[3 - i] = e);
  return arr.reduce((a, b) => a + b);
}

我相信这可以解决您的问题,并且 handleId 可以与任何长度的 id 一起使用。