簡體   English   中英

ReactJS:如何從子組件訪問道具

[英]ReactJS: how to access prop from child component

我正在學習 React.js,並且正在嘗試使用 pokeAPI 創建一個網站。

對於我的一個小部件,我想顯示幾個口袋妖怪及其統計數據。

為此,我有一個主要組件將調用 API 並填充我的 state 數組,然后在 map 中調用 CardPokemon 子組件來顯示每個精靈。

這是我的問題,在我的 web 控制台中,我可以看到我的不同口袋妖怪統計數據 state 數組正在填滿,但在我的主要組件的渲染中,我的數組的值仍然“未定義”。

我試圖實現這個問題的第一個答案: 為什么反應道具未定義傳遞給子組件? 在我的代碼中,但我仍然有同樣的問題,我的數組的值在渲染中保持“未定義”。

我把我的一部分代碼放在這里,任何幫助將不勝感激。

class CardPokemon extends Component {
  render() {
    return (
      <div className="Card">
        <div className="Card__img">
          <img src={this.props.pokemonImgProp[this.props.id]} alt="" />
        </div>
         ...
      </div>
    );
  }
}

class GenerationPokemonStat extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pokemonNameListAPI: [],
      pokemonImgAPI: []
      ...
    };
  }

  searchAllPokemon = () => {
    let number = 151; //for the 151 first pokemon
    Axios.get(`http://localhost:5000/getPokemonByGeneration/allPokemonGen/${number}`)
      .then(res => {
        var i;
        for (i = 0; i < number; i++) {
          let copyNameArray = this.state.pokemonNameListAPI.slice();
          copyNameArray[i] = res.data.results[i].name;
          this.setState({ pokemonNameListAPI: copyNameArray })
          
Axios.get(`http://localhost:5000/getPokemonByGeneration/one_pokemon_gen/${this.state.pokemonNameListAPI[i]}`)
            .then(response => {

              let copyImgArray = this.state.pokemonImgAPI.slice();
              copyImgArray[i] = response.data.sprites.front_default;
              this.setState({ pokemonImgAPI: copyImgArray });
      
              ...

              //everything display normally in web console here
              console.log(response);
              console.log(this.state.pokemonNameAPI[i]);
              console.log(this.state.pokemonImgAPI[i]);
            })
        }
      })
  }

  render() {
    let pokemonNameListAPI = this.state.pokemonNameListAPI;
    let pokemonImgAPI = this.state.pokemonImgAPI;

    //appears to be undefined in web console
    console.log(this.state.pokemonImgAPI[0]);

    if(!pokemonNameListAPI) {
        return null;
    }

    return (
      <>
        <div>
          <button onClick={this.searchAllPokemon}>Search Pokemon</button>
          {pokemonNameListAPI[151] === undefined ? <h1 style={{ textAlign: 'center' }}>Loading...</h1> : (
            <>
              <div className="grid-container">
                {pokemonNameListAPI.map((i) => {

                  //this console.log show me undefined for pokemonImgAPI[i]
                  console.log(pokemonImgAPI[i]);

                  return <CardPokemon
                    key={i}
                    id={i}
                    pokemonImgProp={pokemonImgAPI}
                  />
                })}
              </div>
            </>
          )}
        </div>
      </>
    );
  }
}

export default GenerationPokemonStat;

您不應該在將 state 更新設置為異步執行后立即嘗試讀取 state(請參閱State 更新可能是異步的)。 在您的情況下,這可能意味着第二個 axios 調用沒有獲得您期望的參數並返回 null 結果。

在您的 searchAllPokemon 方法中,當您執行第二個 axios 調用時,請引用 copyNameArray 變量而不是 pokemonNameListApi state 變量。

另外,請記住,每當您更新 state 時,react 都會檢測到 state 更改並導致組件刷新。 您當前正在一個循環中執行兩個 setState 調用。 理想情況下,您應該將結果構造成局部變量並在循環外設置一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM