Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs API数据未被复制并存储到react中的状态,我将如何执行此操作?_Reactjs_Axios_Openweathermap_Jsonplaceholder - Fatal编程技术网

Reactjs API数据未被复制并存储到react中的状态,我将如何执行此操作?

Reactjs API数据未被复制并存储到react中的状态,我将如何执行此操作?,reactjs,axios,openweathermap,jsonplaceholder,Reactjs,Axios,Openweathermap,Jsonplaceholder,所以我是一个新的反应,我有这种困境。我首先使用axios从JSONPlaceholder获取一个“数据库”,然后将其存储在状态中,然后我想调用一个API来填充数据库中不存在的缺失数据。只是简单地运行一下代码,我使用grabdata从JSONPlaceholder中获取所需的数据并将其放入数组中。然后我使用callsetcycle,它调用setcycle方法,该方法应该循环遍历数组位置,获取我需要的数据,然后将其存储在SuggestedDestination数组中。我的问题是,没有调用和存储中的信

所以我是一个新的反应,我有这种困境。我首先使用axios从JSONPlaceholder获取一个“数据库”,然后将其存储在状态中,然后我想调用一个API来填充数据库中不存在的缺失数据。只是简单地运行一下代码,我使用grabdata从JSONPlaceholder中获取所需的数据并将其放入数组中。然后我使用callsetcycle,它调用setcycle方法,该方法应该循环遍历数组位置,获取我需要的数据,然后将其存储在SuggestedDestination数组中。我的问题是,没有调用和存储中的信息,我不明白为什么。任何帮助都将不胜感激

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>
    )
}
导出类应用程序扩展组件{
状态={
建议估计数:[],
计划目标:[],
加载:false
}
componentDidMount=()=>{
这是.grabData()。然后(
这是callsetCycle()
)
}
callsetCycle=()=>{
if(this.state.suggesteddestinations.length>0){
控制台日志(“2”)
这是.setCycle()。然后(
这是我的国家({
加载:正确
}))
}
}
抓取数据=()=>{
返回新承诺(()=>{
变量url=”https://my-json-server.typicode.com/dharquissandas/weatherApp/suggesteddestinations";
获取(url)
.then(contents=>this.setState({suggesteddestinations:contents.data}))
});
}
设置周期=()=>{
返回新承诺(()=>{
变量i
如果(this.state.suggesteddestinations.length>0){
for(i=0;i{
const apicall=等待获取(“http://api.openweathermap.org/data/2.5/weather?q=“+name+”&units=metric&APPID=5AFDBD7139B98AE3F707A76B0DDA2B43B”)
等待apicall.json()
。然后(数据=>
这是我的国家(
此.setCurrentWeatherProperties(数据,位置)
)
)
}
setCurrentWeatherProperties=(数据,位置)=>{
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(名称、位置)=>{
const apicall=等待获取(“http://api.openweathermap.org/data/2.5/forecast?q=“+name+”&units=metric&APPID=5AFDBD7139B98AE3F707A76B0DDA2B43B”)
等待apicall.json()
。然后(数据=>
此.formatForcast(数据,pos)
)
}
formatForcast=(数据,位置)=>{
this.state.suggesteddestinations[pos].dayone=data.list[4]
this.state.suggesteddestinations[pos].daytwo=data.list[12]
this.state.suggesteddestinations[pos].daytree=data.list[20]
this.state.suggesteddestinations[pos].dayfour=data.list[28]
this.state.suggesteddestinations[pos].dayfive=data.list[36]
}
渲染(){
console.log(this.state.suggesteddestinations)
console.log(this.state.loaded)
if(this.state.loaded)返回null;
返回(
{/* 
} /> */}
)
}

}

代码中存在一些问题,状态不能改变,这意味着不能在构造函数之外设置状态。另一个问题是代码设计过度:) 由于您正在学习react,我建议您了解如何从

很好的尝试

以下是实际重构的代码:

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>
        )
    }

}
import React,{Component}来自“React”
导出默认类StackApp60663913扩展组件{
状态={
建议估计数:[],
计划目标:[],
加载:false
}
componentDidMount=()=>{
这是grabData()
}
grabData=async()=>{
让suggestionsApi=”https://my-json-server.typicode.com/dharquissandas/weatherApp/suggesteddestinations";
let suggestionFetch=等待获取(suggestionsApi)
让suggestionData=await suggestionFetch.json()
for(让index=0;index