【问题标题】:Why is promise response getting call twice in functional component? [duplicate]为什么承诺响应在功能组件中被调用两次? [复制]
【发布时间】:2022-01-19 04:20:23
【问题描述】:

我有这个使用承诺的代码,但我的问题是当我 console.log 打印它两次的响应时,这是为什么呢?谁能指出我正确的方向?提前致谢!

import "./App.css";
import { useState } from "react";

function App() {
  const [data, setData] = useState([]);

  let itemsApi = new Promise(function (resolve, reject) {
    setTimeout(() => {
      resolve([
        { grupoId: 1, name: "test1" },
        { grupoId: 2, name: "test2" },
        { grupoId: 1, name: "test3" }
      ]);
    }, 500);
  });

  itemsApi
    .then((res) => {
      console.log(res); // This gets call 2 times, why??
    })
    .catch((error) => {});

  return <div>test</div>;
}

export default App;

【问题讨论】:

  • @AKX 你能提供一个解决方案吗?谢谢!
  • 把有副作用的东西放在useEffect钩子里
  • 它们被称为 function 组件,而不是功能组件。 useState 钩子阻止它发挥作用。

标签: javascript reactjs promise


【解决方案1】:

React 可以随意多次调用您的组件函数(实际上,在严格模式下,它通常会调用它两次,以确保您不会做有副作用的坏事——就像现在一样)。

这是一个如何使用 useEffect 正确进行异步数据加载的示例。

loadData 这里只是一个模拟函数,需要 500 毫秒才能返回数据,但也可以是其他任何东西。

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function loadItems() {
  const data = [
    { grupoId: 1, name: "test1" },
    { grupoId: 2, name: "test2" },
    { grupoId: 1, name: "test3" },
    { grupoId: 1, name: "test4" },
    { grupoId: 3, name: "test5" },
    { grupoId: 2, name: "test6" },
  ];
  await delay(500);
  return data;
}

function App() {
  const [data, setData] = useState([]);
  React.useEffect(() => {
    loadItems().then(setData);
  }, []); // <- empty dependency array has this effect only run once
  return <div>{JSON.stringify(data)}</div>;
}

export default App;

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 2020-12-14
  • 2020-05-08
  • 2020-05-28
  • 1970-01-01
  • 2019-04-29
  • 2021-06-28
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多