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

时间:2017-11-29 15:02:04

标签: 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获取数据:

readableAPI.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)))
    }

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

2 个答案:

答案 0 :(得分:0)

你没有从fetch中返回任何内容:

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

这是你编写fetch(运行它)的方法:

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>

答案 1 :(得分:0)

您确定要正确访问从getCategories返回的对象吗?看起来您的数组位于categories键内:

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