【问题标题】:ReactJS fetch then() not recognizedReactJS fetch then() 无法识别
【发布时间】:2018-04-08 04:01:16
【问题描述】:

我正在使用 ReactJS 构建一个项目,并且正在尝试读取我已经准备好的本地 JSON 文件。

我有一个 app.js 文件,如下所示:

import React, {Component} from 'react';
import fetch from 'isomorphic-fetch'
import './App.css';

class App extends Component {

    getData() {
        return fetch('./examples/test.JSON').then(response => {
           return response.json();
        });
    }

    componentDidMount() {
        console.log(this.getData());
    }

    render() {
        return (
            ...
        );
    }
}

导出默认应用;

getData 函数尝试获取 JSON 文件并返回响应。但是,then() 函数和 json() 函数都无法识别。

是否有我缺少的导入?我以为它们会来自 isomorphic-fetch。

【问题讨论】:

  • “无法识别”是什么意思?你的意思是没有定义?你的错误信息是什么?

标签: reactjs


【解决方案1】:

你期待什么?如果您希望 console.log(this.getData()) 输出您的数据,那么您使用的 fetch 错误。 this.getData() 的结果仍然是一个承诺,因为response.json() 的结果也是一个承诺,而不是实际数据。像这样修改你的代码:

componentDidMount() {
    //console.log(this.getData());
    this.getData().then(jsonData => {
      console.log(jsonData);
    });
}

这就是为什么您在examples for isomorphic-fetch 中看到他们有第二个.then() 方法来使用response.json() 的结果;

fetch('//offline-news-api.herokuapp.com/stories')
    .then(function(response) {
        if (response.status >= 400) {
            throw new Error("Bad response from server");
        }
        return response.json();
    })
    .then(function(stories) {
        console.log(stories);
    });

【讨论】:

    【解决方案2】:

    为什么不使用 axios?

    只需通过npm install --save axios将axios添加到您的项目中

    然后这样做

    ....
    import axios from 'axios';
    ....
    async function getData(){
        const res = await axios.get('./examples/test.JSON');
        console.log(res);
        return res;
    }
    
    render(){
        return(
          <div>{this.getData()}</div>
        )
    }
    

    【讨论】:

      【解决方案3】:

      如果您想从另一个文件中获取数据 JSON 数据,那么您可以直接从该文件中导出该 JSON const 并导入该 cont 并使用它。

      喜欢

      从文件中导出你的 json

      Test.js

      export default const json = {
      A:1, b:2
      //......
      }
      

      在 abc.js 中

      Import json from "Test.js"
      
      Comsole.log(" a is ", json.A)
      // a is 1
      

      我认为 isomorphic-fetch 用于进行 api 调用而不是访问本地文件。

      【讨论】:

        【解决方案4】:

        通读isomorphic-fetch 文档,您会在自述文件的顶部看到一条警告:

        你必须自带兼容 ES6 Promise 的 polyfill,我建议使用 es6-promise。

        尝试按照 README 中的建议安装并包含 polyfill:

        require('es6-promise').polyfill();

        require('isomorphic-fetch');

        我的猜测是这将使.then 工作。

        【讨论】:

          猜你喜欢
          • 2019-01-28
          • 2018-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-20
          • 2021-04-03
          • 1970-01-01
          • 2021-07-01
          相关资源
          最近更新 更多