ComponentDidMount和Axios设置状态之前的组件渲染

时间:2018-11-19 04:17:02

标签: javascript reactjs

好吧,所以在render方法中,我将gifs状态传递给我的GifList组件,问题是当我尝试通过该组件的说法说它的未定义状态并在该组件中使用该数组时,可以看到gifs属性在在setState将其状态设置为生命周期挂钩中我的Axios调用的返回值之前,由于Axios处于异步状态,因此应用程序的状态最初作为空数组传递。我该如何解决这个问题?

import React, { Component } from 'react';
import axios from "axios";
import styles from './App.css';

import Header from './Components/Header/Header';
import GifList from './Components/GifList/GifList';


class App extends Component {

  state = {
    title: "Giphy Search App",
    gifs: []
  }

  componentDidMount() {
     axios.get("http://api.giphy.com/v1/gifs/search? q=funny+cat&limit=20&api_key=ms344CewNH5NEbybHwQifMZImoQfEQ38")
        .then((res) => {
          const arr = res.data.data;
          this.setState({ gifs: arr });
      });
  }

  render() { 
    return (
      <div className={styles.app}>
      <Header title={this.state.title}/>
      <GifList gifList={this.state.gifs}/>
    </div>
  );
 }
}

export default App;

2 个答案:

答案 0 :(得分:0)

您可以等待渲染GrA_X = [10,12,17,16,16,14,12,8] GrA_Y = [10,12,13,7,6,7,8,8] GrB_X = [5,8,13,16,19,15,13,5] GrB_Y = [6,15,12,10,8,9,10,8] Item_X = [6,8,14,18,13,11,16,15] Item_Y = [10,12,8,12,15,12,10,8] scatter_GrA = ax.scatter(GrA_X, GrA_Y) scatter_GrB = ax.scatter(GrB_X, GrB_Y) scatter_Item = ax.scatter(Item_X, Item_Y) def animate(i) : scatter_GrA.set_offsets([[GrA_X[0+i], GrA_Y[0+i]]]) scatter_GrB.set_offsets([[GrB_X[0+i], GrB_Y[0+i]]]) scatter_Item.set_offsets([[Item_X[0+i], Item_Y[0+i]]]) ani = animation.FuncAnimation(fig, animate, np.arange(0,9), interval = 1000, blit = False) ,直到 loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_in_executor(None, update_contacts, { 'email': email, 'access_token': g.tokens['access_token'] }) 数组中包含某些内容。基本上,这是用于jsx的内联if语句。

GifList

答案 1 :(得分:0)

只有列表中包含某些项目,您才能渲染import pandas as pd import numpy as np l=[[{'attr_id': 7, 'val': '4.00'}, {'attr_id': 8, 'val': '2.50'}, {'attr_id': 9, 'val': '1750'}, {'attr_id': 11, 'val': 'false'}, {'attr_id': 10, 'val': 'false'}], [{'attr_id': 7, 'val': '2.00'}, {'attr_id': 8, 'val': '1.00'}, {'attr_id': 11, 'val': 'false'}, {'attr_id': 10, 'val': 'false'}], [{'attr_id': 11, 'val': 'false'}, {'attr_id': 10, 'val': 'false'}],] d = [] for i in l: q={} for x in i: q['attr_id{}'.format(x['attr_id'])]=x['val'] d.append(q) df = pd.DataFrame(d) print(df)

  attr_id10 attr_id11 attr_id7 attr_id8 attr_id9
0     false     false     4.00     2.50     1750
1     false     false     2.00     1.00      NaN
2     false     false      NaN      NaN      NaN

导出默认应用;