在函数调用 Returns API 结果后异步更新状态

Asynchronously Updating State After A Function Call Returns API Results

当从我的 WeatherProvider 调用我的 fetchWeather 函数并向天气发出 axios 请求时,我正在尝试异步更新状态 api。我的请求的结果映射到 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)

现在值将在状态的上下文字段中更新。