函数调用返回API结果后异步更新状态

时间:2018-05-20 01:33:44

标签: javascript reactjs setstate

当我从WeatherProvider调用fetchWeather函数并向天气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>
    )
}
}

1 个答案:

答案 0 :(得分:1)

状态应该设置为,

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

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