API花费的时间太长,数据加载前会触发map函数

时间:2019-03-07 01:04:46

标签: javascript html css reactjs

import React, { Component } from 'react';
import {withProvider} from './TProvider'
import ThreeCardMap from './ThreeCardMap';

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

        this.state = {
            newlist: []
        }
    }


    componentDidMount(){
        this.props.getList()
        this.setState({newlist: [this.props.list]})
    }

    // componentDidUpdate() {
    //     console.log(this.state.newlist);
    // }
    render() {
        const MappedTarot = (this.state.newlist.map((list, i) => <ThreeCardMap key={i} name={list.name} meaningup={list.meaning_up} meaningdown={list.meaning_rev}/>);
        return (
            <div>
                <h1>Three Card Reading</h1>
                <div>{ MappedTarot }</div>
            </div>
        )
        }
    }
export default withProvider(Threecard);

您好,我正在尝试创建一个页面,该页面从tarot卡API(https://rws-cards-api.herokuapp.com/api/v1/cards/search?type=major)中获取数据。不幸的是,等到数据输入时,我的地图功能已经启动。我想看看是否有一种方法可以让map函数等到数据命中后再触发。谢谢!

编辑:上下文中的getList函数:

 getList = () => {
        console.log('fired')
        axios.get('https://vschool-cors.herokuapp.com?url=https://rws-cards-api.herokuapp.com/api/v1/cards/search?type=major').then(response =>{
            this.setState({
                list: response.data
            })
        }).catch(error => {
            console.log(error);
        })
    }

2 个答案:

答案 0 :(得分:2)

this.props.getList()是一个异步函数。您正在该呼叫之后设置列表,这是不正确的。 您需要在getList promise then()块中进行设置。

答案 1 :(得分:1)

getList()是一个异步函数,用于更新父组件的数据。因此,我的解决方案是通过getDerivedStateFromProps

监视来自父组件的list是否更新。

class Threecard extends Component {
  constructor() {
    super();
      this.state = {
        newlist: []
      }
    }
    
  // Set props.list to this.state.newList and watch the change to update
  static getDerivedStateFromProps(nextProps, prevState) {
    return {
      newlist: nextProps.list
    }
  }

  componentDidMount(){
    this.props.getList()
    // Removed this.setState() from here.
  }

  render() {
    const MappedTarot = (this.state.newlist.map((list, i) => <ThreeCardMap key={i} name={list.name} meaningup={list.meaning_up} meaningdown={list.meaning_rev}/>);
    return (
      <div>
          <h1>Three Card Reading</h1>
          <div>{ MappedTarot }</div>
      </div>
    )
  }
}
export default withProvider(Threecard);