首页 > 解决方案 > 我可以在我的 console.log 中显示 API 数据,但我不能用它来设置状态。. . 我该如何设置状态?(获取,反应本机)

问题描述

constructor(props){
    super(props);
    if(myCounter.intCoin == 0){
        this.fetchCoinsAPI("litecoin", "usd");
        this.coinMet("ltc");
    }
    this.state = {
        X: new Animated.Value(0),
        data: undefined,
        arrayLength: undefined,
        line: undefined,
        dataReverse: undefined,
        properties: undefined,
        lineLength: undefined,
        color: "#CDCDCD",
        translate: new Animated.Value(-500), 
        coinColor: {
            btc: {color:"#31055A", selected:false},  
            eth: {color:"#31055A", selected:false}, 
            ltc: {color:"#31055A", selected:false},  
        },
        amountCombined: "USD 0.00",
        currency: "USD ",
        mainCurrency:"usd"
    };
    console.log(this.state.data);
}
fetchCoinsAPI(coinID, currency){
    return fetch(`https://api.coingecko.com/api/v3/coins/${coinID}/market_chart?vs_currency=${currency}&days=7`, {
        method: 'GET'
    })
    .then(res => res.json())
    .then(resp => this.setState({data: resp.prices}))
    .catch(err => {console.log(err)});
}

**我正在从远程 API 获取数据以绘制图表**
它返回undefined状态数据,但是当我console.log(resp.prices).then()它工作时。 我被难住了,有人能指出我错过了什么吗?

谢谢,杰德男孩。

标签: javascriptreactjsreact-nativefetch

解决方案


我想分享三个观察结果。

绑定方法

fetchCoinsAPI使用Component.setState,因此在构造函数中将上下文绑定fetchCoinsAPI到组件

constructor(props){

    this.fetchCoinsAPI = this.fetchCoinsAPI.bind(this);

}

不要在构造函数中调用外部源

把它们放进去componentDidMount

componentDidMount {
    this.fetchCoinsAPI("litecoin", "USD");
}

JavaScript 是异步的

由于 JavaScript 的异步行为,数据将不可用。阅读如何从异步调用返回响应?


推荐阅读