Как мне это сделать, данные API не копируются и не сохраняются в состоянии? - PullRequest
0 голосов
/ 13 марта 2020

Так что я новичок, чтобы реагировать, и у меня есть это затруднительное положение. Сначала я использую ax ios, чтобы получить «базу данных» из JSONPlaceholder, которую затем могу сохранить в состоянии, а затем хочу вызвать API для заполнения недостающих данных, которых не было в базе данных. Просто для быстрого бега кода, я использую grabdata, чтобы получить необходимые данные из JSONPlaceholder и поместить их в массив. Затем я использую callsetcycle, который вызывает метод setcycle, который должен циклически перемещаться по позициям массива и получать нужные мне данные, а затем сохранять их в массиве предполагаемых мест назначения. Моя проблема в том, что информация не вызывается и не хранится, и я не понимаю, почему. Любая помощь будет оценена.

export class App extends Component {
state = {
    suggesteddestinations : [],
    scheduleddestinations : [],
    loaded: false
}


componentDidMount = () =>{
    this.grabData().then(
        this.callsetCycle()
    )
}

callsetCycle = () =>{
    if (this.state.suggesteddestinations.length>0){
        console.log("2")
        this.setCycle().then(
            this.setState({
                loaded: true
        }))
    }
}

grabData = () =>{
    return new Promise(() => {
        var url = "https://my-json-server.typicode.com/dharquissandas/weatherApp/suggesteddestinations";
        Axios.get(url)
        .then(contents => this.setState({ suggesteddestinations: contents.data}))
    });
}

setCycle = () => {
    return new Promise(() => {
        var i
        if (this.state.suggesteddestinations.length > 0){
            for (i = 0; i < this.state.suggesteddestinations.length; i++) {
                console.log("5")
                this.apiCallCurrentWeather(this.state.suggesteddestinations[i].name, i)
                this.apiCallForcast(this.state.suggesteddestinations[i].name, i)
            }
        }
    });
}

apiCallCurrentWeather = async (name, pos) => {
    const apicall = await fetch("http://api.openweathermap.org/data/2.5/weather?q="+name+"&units=metric&APPID=5afdbd7139b98ae3f70a76b0dda2b43b")
    await apicall.json()
    .then(data =>
        this.setState(
            this.setCurrentWeatherProperties(data, pos)
        )
    )
}

setCurrentWeatherProperties = (data, pos) => {
    this.state.suggesteddestinations[pos].temp = data.main.temp.toString()
    this.state.suggesteddestinations[pos].desc = data.weather[0].main
    this.state.suggesteddestinations[pos].tempmax = data.main.temp_max.toString()
    this.state.suggesteddestinations[pos].tempmin = data.main.temp_min.toString()
    this.state.suggesteddestinations[pos].feelslike = data.main.feels_like.toString()
    this.state.suggesteddestinations[pos].pressure = data.main.pressure.toString()
    this.state.suggesteddestinations[pos].windspeed = data.wind.speed.toString()
} 


apiCallForcast = async (name, pos) => {
    const apicall = await fetch("http://api.openweathermap.org/data/2.5/forecast?q="+name +"&units=metric&APPID=5afdbd7139b98ae3f70a76b0dda2b43b")
    await apicall.json()
    .then(data =>
        this.formatForcast(data, pos)
    )
}

formatForcast = (data, pos) => {
    this.state.suggesteddestinations[pos].dayone = data.list[4]
    this.state.suggesteddestinations[pos].daytwo = data.list[12]
    this.state.suggesteddestinations[pos].daythree = data.list[20]
    this.state.suggesteddestinations[pos].dayfour = data.list[28]
    this.state.suggesteddestinations[pos].dayfive = data.list[36]
}


render (){
    console.log(this.state.suggesteddestinations)
    console.log(this.state.loaded)
    if (this.state.loaded) return null;
    return(
        <div>
            <BrowserRouter>
                <div className="container">
                    <Header />
                    {/* <Route path="/" render={(props) =>
                        <Home {...props} suggesteddestinations={this.state.suggesteddestinations} />
                    } /> */}
                    <Route path="/home" component = {Home} exact />
                    <Route path="/CurrentWeather/:id" component = {CurrentWeather} />
                    <Route path="/EventSelection/:id" component = {EventSelection} />
                    <Route path="/Schedule" component = {Schedule} />
                </div>
            </BrowserRouter>
        </div>
    )
}

}

1 Ответ

0 голосов
/ 13 марта 2020

В коде есть несколько проблем. Состояние не может быть видоизменено, что означает, что this.state не может быть установлено вне конструктора. Другая проблема заключается в том, что код перегружен :) Поскольку вы изучаете реакцию, я рекомендую вам понять как методы State Management / Props / жизненного цикла компонентов из реагируют на документацию

Хорошая попытка!

enter image description here

Вот фактический переработанный код:

import React,{Component} from 'react'

export default class StackApp60663913 extends Component {
    state = {
        suggesteddestinations : [],
        scheduleddestinations : [],
        loaded: false
    }


    componentDidMount = () =>{
        this.grabData()
    }

    grabData = async () =>{
        let suggestionsApi = "https://my-json-server.typicode.com/dharquissandas/weatherApp/suggesteddestinations";

        let suggestionFetch = await fetch(suggestionsApi)
        let suggestionData = await suggestionFetch.json()   

        for (let index = 0; index < suggestionData.length; index++) {
            let city = suggestionData[index]

            let weatherFetch = await fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${city.name}&units=metric&APPID=5afdbd7139b98ae3f70a76b0dda2b43b`)   
            let weatherData = await weatherFetch.json()

            let {main,weather,clouds,wind,sys} = weatherData.list[0]

            suggestionData[index].temp = main.temp.toString()
            suggestionData[index].desc = weather[0].description
            suggestionData[index].tempmax = main.temp_max.toString()
            suggestionData[index].tempmin = main.temp_min.toString()
            suggestionData[index].feelslike = main.feels_like.toString()
            suggestionData[index].pressure = main.pressure.toString()
            suggestionData[index].windspeed = wind.speed.toString()

        }

        this.setState({
            suggesteddestinations : suggestionData,
            loaded:true            
        })

    }    

    render (){
        console.log(this.state.suggesteddestinations)
        return(
            <div>
                {this.state.loaded ? 
                <div>
                    {
                        this.state.suggesteddestinations.map((element)=>
                        <li>
                           ID-{element.id},Name-{element.name},Temp-{element.temp},Desc-{element.desc},TempMin-{element.tempmin},TempMax-{element.tempmax} 
                        </li>)
                    }
                </div> :  <div>Loading Data...</div>
                }
            </div>
        )
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...