【问题标题】:How to show the comments from an API which is in tree form in react?如何在反应中显示来自树形 API 的评论?
【发布时间】:2021-10-29 15:28:12
【问题描述】:

API:https://hn.algolia.com/api/v1/items/12701272

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React, { useState } from "react";
// import "./index.css";

const Tree = ({ data = []}) => {
  return (
    <div className="d-tree">
      <ul className="d-flex d-tree-container flex-column">
        {data.map((tree) => (
          <TreeNode node={tree} />
        ))}
      </ul>
    </div>
  );
};

const TreeNode = ({ node }) => {
  const [childVisible, setChildVisiblity] = useState(false);

  const hasChild = node.children ? true : false;

  return (
    <li className="d-tree-node border-0">
      <div className="d-flex" onClick={(e) => setChildVisiblity((v) => !v)}>
        {hasChild && (
          <div
            className={`d-inline d-tree-toggler ${
              childVisible ? "active" : ""
            }`}
          >
            <FontAwesomeIcon icon="caret-right" />
          </div>
        )}

        <div className="col d-tree-head">
          <i className={`mr-1 `}> </i>
          {node.text}
        </div>
      </div>

      {hasChild && childVisible && (
        <div className="d-tree-content">
          <ul className="d-flex d-tree-container flex-column">
            <Tree data={node.children} />
          </ul>
        </div>
      )}
    </li>
  );
};

export default Tree;

我想以树格式显示所有 cmets, 我尝试了上述方法,但它显示错误:TypeError: data.map is not a function tree函数中传入的数据就是转换成数据的api。 怎么办?

【问题讨论】:

  • 您需要检查数据是否为数组。 data.map 不是一个函数意味着它不是一个数组,尝试控制台记录它并检查它是否是一个数组!

标签: javascript reactjs json api


【解决方案1】:

您收到此错误 TypeError: data.map is not a function,因为数据不是数组而是对象。 API 的响应是 -

{
id:12701272,
created_at:"2016-10-13T15:15:48.000Z",
created_at_i:1476371748,
type:"story",
author:"fatihky",
title:"Google's “Director of Engineering” Hiring Test",
url:"http://www.gwan.com/blog/20160405.html",
text:null,
points:1764,
parent_id:null,
story_id:null,
children:(190) [...],
options:(0) [...]
}

注释位于以子元素为键的数组内的对象内。

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2014-07-19
    • 2018-12-15
    • 1970-01-01
    相关资源
    最近更新 更多