React,Fetch API&过滤数据

时间:2018-01-07 18:02:43

标签: javascript reactjs api fetch state

我无法从我提取的网址中获取数据。我试图迭代获取的数组然后计算对象中的总小时数。这是我的API中的示例数组。在渲染之后,我无法使用this.state.users.length计算数组中对象的总长度。因此,我无法从阵列中获取数小时。处理这个问题的最佳方法是什么?我的最终目标是在数组中添加所有小时数然后渲染。

[
 {
   name: "a_example_010618",
   type: "A",
   key: 1,
   hours: 12
 },
 {
   name: "b_example2_010618",
   key: 2,
   type: "B",
   hours: 20
 },
 {
   name: "c_example_010618",
   key: 3,
   type: "C",
   hours: 8
 }
]

我的获取功能:

loadFromApi() {
    fetch('/myAPI')
     .then(response => response.json())
     .then(data => {
         this.setState({ users: data })
     })
     .catch(error => console.log('error fetching', error))
}

尝试将小时数记录到控制台

  countData() {
    console.log('length: ' + this.state.users.length) // returning 0 
    for (let i = 0; i < this.state.users.length; i++) {
      console.log('hours: ' + this.state.users[i].hours) // not running because the length is 0
    }
  }

调用mount:

  componentDidMount() {
    this.loadFromApi()
    this.countData()
  }

然后存储在状态:

  constructor(props) {
    super(props);
    this.state = {
      users: []
    }

    this.loadFromApi = this.loadFromApi.bind(this);
    this.countData = this.countData.bind(this);
  };

渲染示例:

render() {
  console.log('render users: ' + this.state.users); // logs 0 then 3
  console.log('render hours: ' + this.state.users[0].hours); //throws err
  return(
    <div>
      hi
    </div>
  );
}

在渲染功能中,我可以正常调用this.state.users.length并记录值3,但是我无法显示来自api的任何其他数据。

1 个答案:

答案 0 :(得分:0)

设置glTexImage2D后,您是否尝试过调用countData?看起来像这样:

state

loadFromApi() { fetch('/myAPI') .then(response => response.json()) .then(data => { this.setState({ users: data }) this.countData(); }) .catch(error => console.log('error fetching', error)) }

render()

这一行render() { const { users } = this.state; console.log('render users: ' + users); // logs 0 then 3 users && console.log('render hours: ' + users[0].hours); //conditioned rendering return( <div> hi </div> ); } ,简单地说,如果定义了users && console.log('render hours: ' + users[0].hours);,请记录第一批用户users