简体   繁体   English

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

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

I have tried to make an apicall with react code and tried to print the response but it shows error react code我尝试使用反应代码进行 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;

inside app.js在 app.js 里面


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

**folder structure: project: **文件夹结构:项目:
src:源代码:
App.js应用程序.js
components:成分:
apicall.js ** apicall.js **

I got an error in the browser saying, Failed to compile src\components\apicall.js Line 20:21: 'res' is not defined no-undef我在浏览器中出现错误提示,无法编译 src\components\apicall.js Line 20:21: 'res' is not defined no-undef

Note:The link inside fetch() is taken from openweather website注意:fetch() 里面的链接取自 openweather 网站

Can somebody help me with this?有人可以帮我吗?

the issue is you are using the res outside of the then block to solve it add this to the code问题是您正在使用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