反应TypeError:无法读取未定义的属性'length'

时间:2020-04-07 19:20:40

标签: javascript reactjs undefined logical-operators

我正在构建小型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));
  };

你能帮我解决吗?

3 个答案:

答案 0 :(得分:1)

您正在尝试访问该属性,然后再对其进行定义。您可以尝试使用以下代码段吗?

{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}

答案 1 :(得分:0)

您应确保正确调用数据。 这是因为您的数据尚未准备好。

代码应该像这样

{(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>)}

答案 2 :(得分:0)

主要问题是您尝试在实际定义之前使用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一起使用。