javascript - 如何从 fetch API 输出数组中获取不同的值

标签 javascript reactjs fetch

我正在尝试从 API 获取 json 数据并拆分其值并将其填充到我的 React 项目中。服务器 API 的代码如下所示:

const clone = require('clone')
const config = require('./config')

let db = {}

const defaultData = {
  categories: [
      {
        name: 'react',
        path: 'react'
      },
      {
        name: 'redux',
        path: 'redux'
      },
      {
        name: 'udacity',
        path: 'udacity'
      }
  ]
}

function getData (token) {
  //Each token has it's own copy of the DB. The token in this case is like an app id.
  let data = db[token]
  //This populates the default user data if there isn't any in the db.
  if (data == null) {
    data = db[token] = clone(defaultData)
  }
  return data
}

function getAll (token) {
  return new Promise((res) => {
    res(getData(token))
  })
}

module.exports = {
  getAll
}

并且,我正在尝试使用下面所示的代码从上述 API 获取数据:

可读API.js

const url = "http://localhost:3001/"

let token = localStorage.token
if (!token)
  token = localStorage.token = Math.random().toString(46).substr(-8)

const headers = {
  'Accept': 'application/json',
  'Authorization': token
}

export const getCategories = () =>
fetch('http://localhost:3001/categories', {headers})
  .then(res => res.json())
  .then(data => console.log(data))

然后在我的 React 组件中,我尝试获取 API 的结果,如下所示:

import * as readableAPI from './readableAPI.js'

class App extends Component {

componentDidMount() {
  readableAPI.getCategories().then((category) => 
  category.map( value => console.log(value.name)))
}

...

}

现在我面临的问题是:在上面的 componentDidMount() 生命周期方法中的代码中,我可以使用下面给出的代码获取 json 数据:

componentDidMount() {
    readableAPI.getCategories()
}

上面的代码给出了3个类别的数组:

{categories: Array(3)}
   0: {name: "react", path: "react"}
   1: {name: "redux", path: "redux"}
   2: {name: "udacity", path: "udacity"}

但是,如果我尝试映射数组并使用下面的代码获取各个值,我会得到未定义的输出。

componentDidMount() {
      readableAPI.getCategories().then((category) => 
      category.map( value => console.log(value.name)))
    }

我想获取每个类别的值,以便我可以使用服务器中可用的类别名称并将其显示在我的 react 组件中。我哪里出错了。有人可以指导我解决这个问题吗?

最佳答案

您没有从获取中返回任何内容:

fetch('http://localhost:3001/categories', {headers})
  .then(res => res.json())
  .then(data => console.log(data)) // you should return the data (or promise) here

这是编写获取(运行它)的方式:

var root = 'https://jsonplaceholder.typicode.com';
const getCategories = () =>
  fetch(root + '/posts/1', {
    method: 'GET'
  })
  .then(res => res.json())
  .then(data => console.log('inside the fetch - ', data))


getCategories().then((category) => {
  console.log('outside the fetch - ', category);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.min.js"></script>

这是修复(运行它):

var root = 'https://jsonplaceholder.typicode.com';
const getCategories = () =>
  fetch(root + '/posts/1', {
    method: 'GET'
  })
  .then(res => res.json())
  .then(data => {
    console.log('inside the fetch - ', data);
    // you must return the data!
    return data;
  })


getCategories().then((category) => {
  console.log('outside the fetch - ', category);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.min.js"></script>

关于javascript - 如何从 fetch API 输出数组中获取不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47555801/

相关文章:

javascript - 从 0 到 x 的 CSS 宽度转换导致内容压缩

javascript - 错误: Cannot find module 'http-errors' on local npm

javascript - Google 登录按钮电子邮件字段

javascript - Reactjs无法读取https ://cdnjs. cloudflare.com/ajax/libs/babel-core/5.8.23/browser.js:37752:65

使用 div 进行 Javascript Png 透明度 hitTest 检测

javascript - 何时从在 this.props 与 this.state 中存储嵌套组件变量切换

javascript - 在reactjs中显示文件上传成功或失败的消息

node.js - 如何在 "Code by Zapier"中编写 Node 获取(Rest-API)?

spring-data-jpa - 我们可以在 JPA 查询中一起使用 HINT_FETCH_SIZE 和 Pageable 吗

ios - NSUrlConnection 未通过后台获取调用