Асинхронное обновление состояния после вызова функции возвращает результаты API - PullRequest
0 голосов
/ 20 мая 2018

Я пытаюсь асинхронно обновлять состояние, когда моя функция fetchWeather вызывается из моего WeatherProvider и делает запрос 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>
    )
}
}

1 Ответ

0 голосов
/ 20 мая 2018

Состояние должно быть установлено следующим образом:

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

Теперь значение будет обновлено в контекстном поле состояния.

...