javascript - 如何使用 React 映射对象数组的对象数组

标签 javascript arrays json reactjs object

当我 console.log(notes) 时,我有这个 json 格式:

{
  "document_tone": {
    "tone_categories": [
      {
        "tones": [
          {
            "score": 0.027962,
            "tone_id": "anger",
            "tone_name": "Colère"
          },
          {
            "score": 0.114214,
            "tone_id": "sadness",
            "tone_name": "Tristesse"
          }
        ],
        "category_id": "emotion_tone",
        "category_name": "Ton émotionnel"
      },
      {
        "tones": [
          {
            "score": 0.028517,
            "tone_id": "analytical",
            "tone_name": "Analytique"
          },
          {
            "score": 0,
            "tone_id": "tentative",
            "tone_name": "Hésitant"
          }
        ],
        "category_id": "language_tone",
        "category_name": "Ton de langage"
      },
      {
        "tones": [
          {
            "score": 0.289319,
            "tone_id": "openness_big5",
            "tone_name": "Ouverture"
          },
          {
            "score": 0.410613,
            "tone_id": "conscientiousness_big5",
            "tone_name": "Tempérament consciencieux"
          },
          {
            "score": 0.956493,
            "tone_id": "emotional_range_big5",
            "tone_name": "Portée émotionnelle"
          }
        ],
        "category_id": "social_tone",
        "category_name": "Ton social"
      }
    ]
  },
  "idMedia": 25840
}

这是console.log(notes)的图片,我不知道为什么除了预期结果之外我还得到一个空数组

enter image description here

但是当我尝试映射 tone_categories 时,我收到此错误:

TypeError: Cannot read property 'map' of undefined

这是我迄今为止构建的代码:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      notes: [],
    };
  }

componentWillMount() {
  fetch('http://localhost:3000/api/users/analyzeMP3?access_token=GVsKNHWnGWmSZmYQhUD03FhTJ5v80BjnP1RUklbR3pbwEnIZyaq9LmZaF2moFbI6', { 
    method: 'post', 
    headers: new Headers({
      'Authorization': 'Bearer', 
      'Content-Type': 'application/x-www-form-urlencoded'
    }), 
  })
    .then(response => response.text())
    .then(JSON.parse)
    .then(notes => this.setState({ notes }));
}

render() {
  const { notes } = this.state;
  console.log('notes',notes)

  return (

    <div className="App">
     {notes !== undefined && notes !== "" &&  notes !== [] ? notes.document_tone.map((tone_categories, idx) => {
    {console.log('notes',notes.document_tone[tone_categories].category_name)}
     }) : null}  

      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

}

export default App;

最佳答案

您的初始状态是 notes: [],因此在第一次渲染期间数组将为空,如果您尝试从空数组访问项目,则会收到错误。

在这种情况下,更好的方法是具有加载状态并推迟渲染,直到获取数据为止:

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      notes: [],
      loading: true // Set the loading to true initially
    };
  }

  componentDidMount() {
    fetch(
      "http://localhost:3000/api/users/analyzeMP3?access_token=GVsKNHWnGWmSZmYQhUD03FhTJ5v80BjnP1RUklbR3pbwEnIZyaq9LmZaF2moFbI6",
      {
        method: "post",
        headers: new Headers({
          Authorization: "Bearer",
          "Content-Type": "application/x-www-form-urlencoded"
        })
      }
    )
      .then(response => response.text())
      .then(JSON.parse)
      .then(notes => this.setState({ notes, loading: false })); // reset the loading when data is ready
  }

  render() {
    const { notes, loading } = this.state;
    console.log("notes", notes);

    return loading ? (
      <p>Loading...</p> // Render the loader if data isn't ready yet
    ) : (
      <div className="App">//...</div>
    );
  }
}

关于javascript - 如何使用 React 映射对象数组的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58064778/

相关文章:

javascript - CSS:如果表头悬停,如何在表的每个单元格上触发悬停?

javascript - Angular 提交处理程序不将数据记录到控制台

json - 如何通过billboard API获取 "billboard hot 100"图表列表

java - 查找大小,即存储在 Java 数组中的非空元素的数量

javascript - 根据每个对象的 id 重新排序数组

ios - 如何使用SwiftyJSON读取数组中的JSON数据?

javascript - 将每个函数与 getJSON 一起使用内部文件

javascript - 使用 R 从 Javascript 检索文本(html 节点)

javascript - 在 JavaScript 中从工作日获取下一个日期

c - 指针、数组和函数