使用React钩子显示jsonplaceholder api中的数据

时间:2020-01-13 22:21:00

标签: javascript reactjs react-hooks

我有简单的rest api,我试图显示jsonplaceholder假api中的用户

这是我的功能组件

import React, {useState, useEffect} from "react";
import axios from 'axios';

 export default function TableList() {

  const [data, setData] = useState({ hits: [] });

    useEffect(() => {
      const fetchData = async () => {
        const result = await axios(
          'https://jsonplaceholder.typicode.com/users',
        );
        setData(result.data);
          console.log(result.data);
      };
      fetchData();
    }, []);


  return (
    <div>
      <ul>
            {data.hits.map(item => (
              <li key={item.id}>
              <h1>{item.name}</h1>
              </li>
            ))}
          </ul>

    </div>

  );
}

不幸的是,我收到以下错误:

TableList.js:22 Uncaught TypeError: Cannot read property 'map' of undefined

我的代码有什么问题?

2 个答案:

答案 0 :(得分:3)

您错误地设置了数据,应该对data.hits进行空检查。这是一个可行的例子

function TableList() {
  const [users, setUsers] = useState({ hits: [] });

  useEffect(() => {
    const fetchData = async () => {
      const { data } = await axios(
        "https://jsonplaceholder.typicode.com/users"
      );
      setUsers({ hits: data });
    };
    fetchData();
  }, [setUsers]);

  return (
    <div>
      <ul>
        {users.hits &&
          users.hits.map(item => (
            <li key={item.id}>
              <span>{item.name}</span>
            </li>
          ))}
      </ul>
    </div>
  );
}

https://codesandbox.io/s/affectionate-lehmann-17qhw

答案 1 :(得分:0)

“命中”是必需的吗?。

file3