0

我正在尝试为 API 中的每个类别显示不同的卡片(名称、子类别...)。但我看不到 API 中的值是什么。例如,我不知道 ID 是什么,或者如果类别名称是 .title 或 .name 怎么办,所以我无法显示它。

https://www.ifixit.com/api/2.0/categories

在 API 上,我可以看到类别的名称,但没有“ID”、“NAME”、“KEY”……所以当我尝试显示它时,我不知道如何访问该名称。

componentDidMount() {
axios.get('/categories')
    .then(res => {
      const categories = res.data; //How do I get the "ID" from here?
      this.setState({categories: categories});
      })
}
4

4 回答 4

0

将其夹在您的控制台中以查看它可能是什么。

componentDidMount() {
axios.get('/categories')
    .then(res => {
      const categories = res.data; //How do I get the "ID" from here?
      console.log({res, categories}) // Try this!
      this.setState({categories: categories});
      })
}
于 2019-09-05T08:24:48.527 回答
0

您的 CDM 将存在于您的类中,因此您还将有一个 render() 方法:

render() {
  return (
    {Object.keys(this.state.categories).map((key) => {
      <p><span>{key}</span><span>{this.state.categories[key]}</span></p>
    }
  );
}

这将显示一个键列表及其数据中的值。

于 2019-09-05T08:25:56.890 回答
0

如果您尝试示例代码,如下所示:

componentDidMount() {
    const endpoint = 'https://www.ifixit.com/api/2.0/categories';

    fetch(endpoint).then(res => console.log(res.json()));
}

通过单击 (F12) 打开控制台,您将看到返回一个Promise,但ID对象不存在。

在此处输入图像描述

于 2019-09-05T08:34:40.310 回答
0

将 res.data 分配给状态后

axios.get('/categories')
      .then(res => { this.setState({ categories: res.data }) })
      .catch(err => { console.log(err) })

您可以 console.log "this.state.categories" 并查看是否有任何 id/name 详细信息。

这取决于您的数据库。

编辑:

当我检查您的 API 时,没有 id 字段。因此,您无法访问该 ID。但;

this.state.categories.Apparel

会给你 Apparel 对象。您可以使用对象中的唯一项作为键。

于 2019-09-05T08:27:32.880 回答