簡體   English   中英

函數調用后返回API結果的異步更新狀態

[英]Asynchronously Updating State After A Function Call Returns API Results

當我從WeatherProvider調用fetchWeather函數並向Weather api發出axios請求時,我試圖異步更新狀態。 我請求的結果映射到fetchWeather函數中的一個預測變量。

我想將預報數組的新狀態設置為fetchWeather函數的預報結果。 我嘗試過以各種方式使用setState,但是仍然無法更新狀態。 我這是怎么了?

import React from 'react' 
import axios from 'axios'
import _ from 'lodash'

export const WeatherContext = React.createContext();

export class WeatherProvider extends React.Component {
constructor(props) {
    super(props)

    this.state = {
        context: {
            input: '',
            forecast: [],
            fetchWeather: WeatherProvider.fetchWeather
        }
    }

    this.fetchWeather = this.fetchWeather.bind(this)
}

fetchWeather = (term) => {
    let QUERY = term;
    const KEY = `key`
    let URL = `http://api.openweathermap.org/data/2.5/forecast?q=${QUERY}&appid=${KEY}`

    axios.get(URL)
    .then( res => {
        const forecast = _.flattenDeep(Array.from(res.data.list).map((cast) => [{
            date: cast.dt_txt, 
            temp_min: cast.main.temp_min,
            temp_max: cast.main.temp_max,
            group: cast.weather[0].main,
            detail: cast.weather[0].description,
            icon: cast.weather[0].icon
        }]) )

        this.setState(() => {
           forecast: forecast
        },() => { console.log(forecast, this.state.context.forecast) 
    })
}

render() {
    return (
        <WeatherContext.Provider value={{ ...this.state.context, fetchWeather: this.fetchWeather }} >
            { this.props.children }
        </WeatherContext.Provider>
    )
}
}

狀態應設置為

 .then( res => {
    ...
        let tempConetxt = {...this.state.context}
    tempContext.forecast = forecast;
        this.setState({context: tempContext},() => { console.log(forecast, this.state.context.forecast)

現在,值將在狀態的上下文字段中更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM