首页 > 解决方案 > 这两个数组有什么区别,如何访问我需要的属性?

问题描述

我正在使用 PokeAPI 进行 PokeDex 项目,并且可以使用您的帮助。在尝试处理从 API 接收到的 json 时,我遇到了两种看似不同的数组类型:

数组的控制台表示

打开的数组

例如,我能够检索第一种类型数组的名称和 url,但无法和/或不确定如何检索bulbasaur 的类型值。

我认为这与我填充数组的不同方式有关,但不确定。

这是我的代码:

class App extends Component {
constructor() {
  super();

  this.state = {
    pokemonArray: [],
    pokemonInfoArray: [],
    searchfield: '',
  }
}

componentDidMount() {
  this.fetchKantoDex()
}
// Fetches the pokemon that reside in Kanto.
fetchKantoDex = () => {
  fetch('https://pokeapi.co/api/v2/pokemon?limit=10')
    .then(response => response.json())
    .then(data => this.setState({ pokemonArray: data.results}))
    .then(this.fetchSinglePokemon)
}

// Is called by other fetch methods. Loops through and fetches the information pertaining to
// each pokeon fetched, and stores their info in a seperate array.
fetchSinglePokemon = () => {
  let tempInfo = [];
  for(let i = 0; i < this.state.pokemonArray.length;i++){
    let url = this.state.pokemonArray[i].url;
      fetch(url)
      .then(response => response.json())
      .then(pokedata => tempInfo.push(pokedata))
      .then(pokedata => console.log(pokedata.results))

  } 
  this.setState({ pokemonInfoArray: tempInfo})
  // console.log(this.state.pokemonArray)
  console.log(this.state.pokemonInfoArray)
}

标签: javascriptarraysjsonreactjsfrontend

解决方案


演示如何实现。还有一些其他问题必须通过您的 Promise 回调来解决,如果您希望它在获取对象后立即尝试渲染对象,您可以使用 then 并立即将它们添加到状态数组或使用 async/await 和一个 for await 循环:

const {Component} = React
const {render} = ReactDOM

class App extends Component {
  constructor() {
    super();

    this.state = {
      pokemonArray: [],
      pokemonInfoArray: [],
      searchfield: '',
    }
  }

  componentDidMount() {
    this.fetchKantoDex()
  }
  // Fetches the pokemon that reside in Kanto.
  fetchKantoDex = () => {
    fetch('https://pokeapi.co/api/v2/pokemon?limit=1')
      .then(response => response.json())
      .then(data => this.setState({
        pokemonArray: data.results
      },this.fetchSinglePokemon))
      // use setState callback, guarantees state is updated before calling fetchSingle, although what you really should do is build all the data before using setState, unless you need state to be updated like this for your components
  }

  // Is called by other fetch methods. Loops through and fetches the information pertaining to
  // each pokeon fetched, and stores their info in a seperate array.
  fetchSinglePokemon = () => {
    let tempInfo = [], fetchArray = [];
    console.log(this.state.pokemonArray)
    for (let i = 0; i < this.state.pokemonArray.length; i++) {
      let url = this.state.pokemonArray[i].url;
      fetchArray.push(
       fetch(url)
        .then(response => response.json())
        .then(pokedata => {
          //tempInfo.push(pokedata)
          return pokedata
          // modified to resolve Promise with tempInfo as value
        })
      )
    }
    //for(const info of await fetchArray)
    Promise.all(fetchArray).then(infoArray => {console.log(infoArray)
      this.setState({
        pokemonInfoArray: infoArray
      })
    })
  }
  
  render() {
    return this.state.pokemonInfoArray.map((info,i) => <div key={i}>{JSON.stringify(info)}</div>)
  }
}


render(<App/>,document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>


推荐阅读