简体   繁体   English

使用 PokeApi 给孩子 React Pass 道具

[英]React Pass props to children with PokeApi

I building small React App with PokeApi .我用PokeApi构建小型 React App。 So, I want to creating Pokedex App.所以,我想创建 Pokedex 应用程序。 My problem is that pokemon.name doesnt display on screen.我的问题是pokemon.name没有显示在屏幕上。 I will show you.我给你看。 So, when I clicked on pokeCard, in SelectedPokemon props saved id of clicked pokeCard.所以,当我点击 pokeCard 时,在 SelectedPokemon 道具中保存了点击的 pokeCard 的 id。 But, I dont know why,when I doing fetch and passing pokemon props, in children's props I see only array of pages of pokemons instead pokemon.name .但是,我不知道为什么,当我获取和传递 pokemon 道具时,在儿童道具中,我只看到 pokemon 页面数组而不是pokemon.name

图鉴索引

. .

Its code of Parent component.它的父组件代码。 I think, that problem may be in fetch.我认为,这个问题可能正在发生。

Parent component父组件

function About(props) {
  let { SelectedPokemon } = props;
  const [Pokemon, setPokemon] = useState([]);
  const [Loading, setLoading] = useState(true);

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

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

  return (
    <div
      style={{
        position: "fixed",
        top: 150,
        right: 150,
      }}
    >
      <PokemonDetails pokemon={Pokemon} />
    </div>
  );
}

Its Children Component :它的子组件

function PokemonDetails(props) {
  let { pokemon } = props;
  return (
    <div style={{ border: "1px solid #333", height: "300px", width: "250px" }}>
      {pokemon.name}
    </div>
  );
}

I solved my problem.我解决了我的问题。

My Pokemon is array.我的Pokemon是数组。 So I to loop over it.所以我要循环它。

{pokemon.map((pokemon) => ( <div key={pokemon.id}>{pokemon.name}</div> ))}

When I setting setPokemon([...Pokemon, result]) means implementation as new collection.当我设置setPokemon([...Pokemon, result])意味着实现为新集合。 I set setPokemon([...Pokemon, result]) and all works.我设置setPokemon([...Pokemon, result])并且一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM