在 React JS 中显示来自 api 的数组列表

Display array list from api in React JS

我是 React 的新手,我正在尝试在有序列表中显示来自此 api 的数组列表。这是我从 Chuck Norris.

得到它的 link
[
  "animal",
  "career",
  "celebrity",
  "dev",
  "explicit",
  "fashion",
  "food",
  "history",
  "money",
  "movie",
  "music",
  "political",
  "religion",
  "science",
  "sport",
  "travel"
]

这是我的示例代码

import React from 'react';
import PropTypes from 'prop-types';

GetList.propTypes = {
    categoriesList: PropTypes.array,
};
GetList.defaultProps = {
    categoriesList:[],
}

function GetList(props) {
    const {categoriesList} = props;
    return (
        <ul className="post-list">
            {categoriesList.map(post=>(
                <li></li>
            ))}
        </ul>
    );
}

export default GetList;

这是我进行 api 调用的 App.js 代码

function App() {
  const [categoriesList, setCategoriesList] = useState([]);
  useEffect(() => {
    async function fetchCategoriesList(){
      try{
        const requestUrl = 'https://api.chucknorris.io/jokes/categories';
        const response = await fetch(requestUrl);
        const responseJSON = await response.json();
        console.log(responseJSON);
        setCategoriesList(responseJSON);
      } catch {

      }
    }

    fetchCategoriesList();
  }, [])
  return (
    <div className="App">
      <GetList />
    </div>
  );
}

它获取数据,我可以从 console.log 看到它,但它没有显示。我怎样才能显示列表?

您需要将道具 (categoriesList) 传递给您的 GetList 组件:

<div className="App">
  <GetList categoriesList={categoriesList} />
</div>;

并且在您的组件中,您还需要从数组中渲染一些东西:

<ul className="post-list">
  {categoriesList.map(post => (
    <li>{post}</li>  // <-- Here, need to put individual post
  ))}
</ul>;