无法循环遍历数组对象以创建列表项

时间:2018-01-10 05:58:25

标签: javascript arrays reactjs dictionary

我能够循环遍历JSON数据来创建一个充满数字的数组,但是当我去创建列表项时,它不起作用。该组件只是呈现一个空列表。

当我在map函数之前的console.log(ticketNumbers)时,它显示为折叠的Array [],直到我展开它(然后显示所有值)

function apiCall() {
  var ticketNumbers = [];
  var memId = 'xxx'; 
  var myInit = { 
      method: 'GET',
      mode: 'cors',
      headers: {
        'authorization': "xxx",
    'Access-Control-Allow-Origin':'*',
    'content-type': "application/json",
    'cache-control': "no-cache"
          },
      params: {
    'orderBy': 'status/name asc',
    'pageSize': 300,
    'conditions': "resources contains '" + memId + "' AND status/id not in (17,165,36,163,164,42,73,46,78,148,34,132,45,159,60,168,106,51,72,95)"
          }
  };
  axios.get('Url', myInit)
    .then((response) => {
      console.log(response.data)
      for (var ticket in response.data) {
        ticketNumbers.push(response.data[ticket].id)
      };  
     })
    return ticketNumbers
}
class TicketContainer extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data: [],
      loading: true,
    };
  }
  componentWillMount() {
      this.setState({
        data: {
      numbers: apiCall()
        },      
      loading: false
        })
      };
  render() {
    return(
      <div>
    {this.state.loading ? 'Loading' : <Tickets data={this.state.data} />}
      </div>
    )
  }
}

class Tickets extends Component {
  render() {
    const stuff = this.props;
    var ticketList = stuff.data.numbers;
    console.log(ticketList);
    return(
      <div>
        <ul>Ticket Number
          {ticketList.map((ticket, index) => {
            return <li key={index}>sweet</li>;
          })}   
        </ul>
      </div>
    );
  }
}

2 个答案:

答案 0 :(得分:0)

你应该正确使用Promise来解决这个问题。首先,让我们改变apiCall,以便它返回一个Promise:

function apiCall() {
  var ticketNumbers = [];
  var memId = 'xxx'; 
  var myInit = { 
      method: 'GET',
      mode: 'cors',
      headers: {
        'authorization': "xxx",
    'Access-Control-Allow-Origin':'*',
    'content-type': "application/json",
    'cache-control': "no-cache"
          },
      params: {
    'orderBy': 'status/name asc',
    'pageSize': 300,
    'conditions': "resources contains '" + memId + "' AND status/id not in (17,165,36,163,164,42,73,46,78,148,34,132,45,159,60,168,106,51,72,95)"
          }
  };
  return axios.get('Url', myInit)
    .then((response) => {
      console.log(response.data)
      for (var ticket in response.data) {
        ticketNumbers.push(response.data[ticket].id)
      }
      return ticketNumbers;
     });
}

你知道有一个基于Promise的api可以像这样使用:

apiCall().then(ticketNumbers => console.log(ticketNumbers);

我们只需要修改componentWillMount:

componentWillMount() {
     apiCall().then(numbers => this.setState({ loading: false, data: numbers });
}

答案 1 :(得分:0)

apiCall函数调用一个异步进程的API,并从函数请求返回ticketNumbers而不返回结果,因为在API响应之前将执行return语句ready和ticketNumbers数组已填充。

最简单的方法是在React类中定义此函数,并在setState请求的回调中直接axios

class TicketContainer extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data: [],
      loading: true,
    };
  }
  componentWillMount() {
      this.apiCall()

  };


  apiCall =() => {

      var memId = 'xxx'; 
      var myInit = { 
          method: 'GET',
          mode: 'cors',
          headers: {
            'authorization': "xxx",
            'Access-Control-Allow-Origin':'*',
            'content-type': "application/json",
            'cache-control': "no-cache"
          },
          params: {
            'orderBy': 'status/name asc',
            'pageSize': 300,
            'conditions': "resources contains '" + memId + "' AND status/id not in (17,165,36,163,164,42,73,46,78,148,34,132,45,159,60,168,106,51,72,95)"
              }
      };
      axios.get('Url', myInit)
        .then((response) => {
          var ticketNumbers = [];
          for (var ticket in response.data) {
            ticketNumbers.push(response.data[ticket].id)
          }; 
          this.setState({data: ticketNumbers, loading: false}) 
         })
  }
  render() {
    return(
      <div>
    {this.state.loading ? 'Loading' : <Tickets data={this.state.data} />}
      </div>
    )
  }
}

class Tickets extends Component {
  render() {
    const stuff = this.props;
    var ticketList = stuff.data.numbers;
    console.log(ticketList);
    return(
      <div>
        <ul>Ticket Number
          {ticketList.map((ticket, index) => {
            return <li key={index}>sweet</li>;
          })}   
        </ul>
      </div>
    );
  }
}

如果您想知道为什么console.log()语句记录数组,请检查此答案Value below was evaluated just now in JavaScript object