繁体   English   中英

使用 REACTJS 中的 fetch() function 进行 API CALL 时未加载数据

[英]Data not loaded when API CALL made using fetch() function in REACTJS

我尝试使用反应代码进行 apicall 并尝试打印响应,但它显示错误反应代码


    import React,{Component} from 'react'
    
    class ApiCall extends Component 
    {
        constructor(props)
        {
            super(props);
            this.state=
            {
                items:[],
                isloaded:false,
            }
        }
    
        componentDidMount()
        {
            fetch('api.openweathermap.org/data/2.5/weather?q=chennai&appid=e407e5e8......')
            .then(res=>res.json())
            console.log(res.json())
            .then(json=>{
                 this.setState({
                     isloaded:true,
                     items: json,
                 })
            });
        }
    
        render()
        {
            var{isloaded,items}=this.state;
    
            if(!isloaded)
            {
                return <div>Loading..</div>;
            }
            else
            {
            return(
                <div>
                   Data Loaded
                   <ul>
                       {items.map(item=>(
                           <li key={item.id}>
                               Title: {item.title  }
                               Body:{item.body}
                           </li>
                       ))};
                   </ul>
                </div>
            )
            }
        }
    }
    
    export default ApiCall;

在 app.js 里面


    class App extends Component 
    {
      render()
      {
        return(
          <div className="App">
            <ApiCall/>
          </div>
        )
      }
    }

**文件夹结构:项目:
源代码:
应用程序.js
成分:
apicall.js **

我在浏览器中出现错误提示,无法编译 src\components\apicall.js Line 20:21: 'res' is not defined no-undef

注意:fetch() 里面的链接取自 openweather 网站

有人可以帮我吗?

问题是您正在使用then块之外的res来解决它,将其添加到代码中

.then((res) => {
    console.log(res.json());
    return res.json();
 })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM