鍍金池/ 問答/HTML/ 使用map遍歷執(zhí)行axios網(wǎng)絡(luò)請(qǐng)求push到數(shù)組后,通過數(shù)組[0]取值為und

使用map遍歷執(zhí)行axios網(wǎng)絡(luò)請(qǐng)求push到數(shù)組后,通過數(shù)組[0]取值為undefined.

我在寫React應(yīng)用,通過map遍歷執(zhí)行axios網(wǎng)絡(luò)請(qǐng)求后將請(qǐng)求結(jié)果push到一個(gè)數(shù)組,請(qǐng)求完了以后數(shù)組可以正常輸出,但是通過array[0]取出來的值為undefined,請(qǐng)各位大神幫忙看看什么原因。

代碼:

import React, { Component } from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hosMsgList: []
    }
  }
  componentDidMount() {
    axios.post('/12320yywz/Region/findHosListByQueryTypeAndAreaCode', 'serviceId=orgService&method=findHosListByQueryTypeAndAreaCode&queryType=1&areaCode=5202&body%5B%5D=&body%5B%5D=&body%5B%5D=&body%5B%5D=&body%5B%5D=5202&body%5B%5D=0',{
      headers:{
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then((res)=>{
      let hosMsgList = [];
      res.data.msg.map((hos) => {
        axios.post('/12320yywz/Hospital/hospitalMessage2','appid=1232074657672961822621734470&queryType=1&orgCode='+hos.orgCode, {
          headers:{
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          }
        }).then((hosMsg) => {
          hosMsgList.push(hosMsg.data.msg[0].address);
          // let hosMsgList = this.state.hosMsgList;
          // hosMsgList.push(hosMsg.data.msg[0]);
          // this.setState({hosMsgList});
        }).catch((err)=>{
          console.log('hospitalMessage2 Error' + err);
        })
      });
      return hosMsgList;
    }).then((hosMsgList)=>{
      console.log(hosMsgList);
      console.log(hosMsgList[0]);
    }).catch((err)=>{
      console.log("findHosListByQueryTypeAndAreaCode Error", err);
    })
  }
  render() {
    if(this.state.hosMsgList.length !== 0){
      console.log(this.state.hosMsgList[0]);
    }
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

clipboard.png

可以看到console.log(hosMsgList)打印出一個(gè)數(shù)組,但是通過console.log(hosMsgList[0]);打印的值為undefined,請(qǐng)各位大神幫忙分析分析是什么原因,感謝!

回答
編輯回答
爛人

你的axios請(qǐng)求用了2個(gè)then回調(diào)?

2017年9月30日 19:36