【问题标题】:How to get json data using fetch in react如何在反应中使用 fetch 获取 json 数据
【发布时间】:2019-09-23 21:42:11
【问题描述】:

我正在使用 react 并致力于在组件中获取 json 文件。

我想使用 fetch 获取 input.json 文件,但它不是控制台中的数据。为什么会这样?如何获取数据?

输入.json

{
    "formId": 1,
    "title": "from",
    "items": [{
      "itemId": 1,
      "title": "style",
      "formType": 1,
      "options": [{
        "id": 1,
        "text": "one"
      }, {
        "id": 2,
        "text": "two"
      }, {
        "id": 3,
        "text": "three"
      }]
    }

App.js

import React from 'react';
import './App.css';
import inputData from './assets/input.json';

function App() {

  const getData = () => {
    fetch(inputData).then(response => {
               return response;
             }).then(data => {
               console.log(data);
             }).catch(err => {
               console.log(err)
             });
  }

  getData();

  return (
    <div className="App">
      <h2>Fetch</h2>
    </div>
  );
}

export default App;

console.log

【问题讨论】:

标签: fetch


【解决方案1】:

试试这个,

import React from 'react';
import './App.css';
import inputData from './assets/input.json';

function App() {

  const getData = () => {
    fetch(inputData).then(response => {
                console.log(response);
                console.log(response.data);
              }) catch (err => console.log("err",err))
  }

  getData();

  return (
    <div className="App">
      <h2>Fetch</h2>
    </div>
  );
}

export default App;

【讨论】:

  • 感谢您的回答。但这是一回事。
【解决方案2】:

你在获取结果时遗漏了一些东西,应该是

 fetch(inputData).then(response => {
            response.json().then(data => {
            console.log(data);
          }).catch(err => {
            console.log(err)
          });


【讨论】:

    【解决方案3】:

    您是否尝试过将响应解析为 json 格式?

    类似这样的:


    import inputData from '../assets/input';
    
    const getData = () => {
     fetch(inputData).then(response => {
    const result = response.json()
                return result;
              }).then(data => {
                console.log(data);
              }).catch(err => {
                console.log(err)
              });
    }

    【讨论】:

    • 执行response.json()时出错,因为它已经是一个json文件。谢谢你的回答!
    猜你喜欢
    • 2021-05-23
    • 2019-07-14
    • 2020-06-28
    • 2015-07-15
    • 1970-01-01
    • 2017-12-27
    • 2017-05-11
    • 1970-01-01
    • 2021-06-03
    相关资源
    最近更新 更多