【问题标题】:React hook with fetch api使用 fetch api 反应钩子
【发布时间】:2019-08-03 07:43:12
【问题描述】:

我想做一个非常简单的 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

【问题讨论】:

  • 我认为您走在正确的道路上,除了已经给出的建议。除此之外,我还要指出,您可以选择在 .then 链接上使用 async await。但是,您需要确保异步不会泄漏到 useEffect 函数参数,因为它会抱怨返回的承诺。

标签: reactjs axios fetch react-hooks


【解决方案1】:

首先你需要改变这一行

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

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

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

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

.then(res => setTodos(res))

然后您可以在返回中映射您的todos

here's and example

【讨论】:

    猜你喜欢
    • 2021-01-16
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多