javascript - 如何在ReactJS中获取json数据并根据响应渲染组件(List)

标签 javascript reactjs

我想从 /list 加载图书列表(图书文件)端点并将它们列在 <ul> 中。我创建了一个列表组件,然后将其导入 index.jsx 。但这不起作用。如何使用从服务器获取的 json 数据在 body 中渲染组件?

list.component.jsx:

import React from 'react'

class List extends React.Component {
  constructor() {
    super()
    this.state = { files: [] }
  }

  componentDidMount() {
    let files = []

    fetch('/books', {
      method: "POST",
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
      },
      body: JSON.stringify({ dir: '/' })
    })
      .then(response => response.json())
      .then(data => {
        this.setState({ files: data.books })
      })
  }

  render() {
    return (
      <div>
        <h1>Book List</h1>
        <ul>
          {this.state.files.map(book => {
            return <li key={`book-${book.id}`}>{book.name}</li>
          })}
        </ul>
      </div>
    )
  }
}

export default List

index.jsx:

import List from '../components/list'

document.addEventListener('DOMContentLoaded', () => {
  ReactDOM.render(
    <List/>,
    document.body.appendChild(document.createElement('div')),
  )
})

我看到“网络”选项卡中提取了“/list”,但浏览器上没有数据。

给出的错误:

list.jsx:31 Uncaught TypeError: this.state.files.map is not a function
    at List.render (list.jsx:31)
list.jsx:31 Uncaught (in promise) TypeError: this.state.files.map is not a function
    at List.render (list.jsx:31)

最佳答案

您是否在 setState 命令之前直接尝试过 console.log 语句?可能值得检查数据,然后检查数据书籍。您的数据实际上可能位于 data 而不是 data.books 中。 data.books 可能是一个字符串,您可能需要 JSON.parse 将其转换为数组。

关于javascript - 如何在ReactJS中获取json数据并根据响应渲染组件(List),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55609051/

相关文章:

javascript - 如何在命令行上将文件名传递给 emscripten 编译的节点脚本?

javascript - React Router 2 更高效的路由

reactjs - 覆盖 MUI 芯片删除图标颜色

javascript - Javascript 中的空合并?

javascript - 从 GWT 代码调用 getElementsByTagNameNS

javascript - 在不同的列中显示 JSON 结果 Angular JS

javascript - 如何使 React Portal 与 React Hook 配合使用?

javascript - 梅文本字段。更改图标时,无法点击

reactjs - RCTLogInfo(来自 React/RCTLog)将输出发送到哪里?

Javascript window.open() 与 php 代码