使用 fetch api 反应钩子

React hook with fetch api

我想做一个非常简单的Fetch请求(或者axios请求),然后映射这些结果。

为此,我使用了 useState 和 useEffect,但我肯定做错了什么。

 function App() {
  const [todos, setTodos] = useState({});

  const getTodos = () => {
    const urlTodos = "https://jsonplaceholder.typicode.com/todos/";
    return fetch(urlTodos)
      .then(res => res.json())
      .then(res => {
       return res 
      });
  };

  useEffect(() => {
    getTodos().then(setTodos);
  }, []);

  const [todosSimple, setTodosSimple] = ([
    {
      text: 'learn about react',
      isCompleted :true
    },
    {
      text: 'Danse',
      isCompleted: false
    }
  ])

  console.log(todosSimple)


  return (
    <div className="App">
      {todosSimple.map((todo,index) => {
        return todo;     
      }  
      )}

    </div>
  );
}

Codesandbox

首先你需要改变这一行

const [todos, setTodos] = useState({});

const [todos, setTodos] = useState([]);

因为 todos 变量将具有默认值,并且它将是一个空对象。对象上没有 .map 方法,而且您从 api 接收到一个数组。

其次,我建议最后在 getTodos 中使用 setTodos 函数。

.then(res => setTodos(res))

然后您可以将您的 todos 映射到 return

here's and example