next.js 点击按钮后,fetch方法被无休止地调用[重复]

sbdsn5lh  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(123)

此问题已在此处有答案

How to async await in react render function?(2个答案)
5天前关闭。
我想在“使用客户端”页面. tsx中使用模态。我用这个例子来说明:https://www.creative-tim.com/learning-lab/tailwind-starter-kit/documentation/react/modals/regular.但是,如果我点击按钮,我的fecth调用被设置在一个无限循环中,并无限期地调用,应用程序挂起。有什么问题吗?我在13.4.3版本中使用Next。
app/page.tsx:

"use client";

export default async function Home() {
const [showModal, setShowModal] = useState(false);

const result = await fetch(`http://localhost:3000/products`, {
 cache: "no-store",
}).then((res) => res.json());

  <button
      className="bg-pink-500 text-white active:bg-pink-600 font-bold uppercase text-sm px-6 py-3 rounded shadow hover:shadow-lg outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150"
      type="button"
      onClick={() => setShowModal(true)}>
      Open regular modal
  </button>
...

}

点击按钮后:

9o685dep

9o685dep1#

你在组件的每一次呈现上都发出了一个 AJAX 请求。这可能不是你想要的
相反,使用useEffectfirst 呈现时(或者在给定的依赖项集发生更改的任何时候,这里似乎不是这种情况)发出 AJAX 请求,并使用结果更新状态。例如:

export default function Home() {
  const [showModal, setShowModal] = useState(false);
  const [result, setResult] = useState();

  useEffect(function () {
    (async function() {
      const res = await fetch(`http://localhost:3000/products`, {
        cache: "no-store",
      });
      const json = await res.json();
      setResult(json);
    })();
  }, []);

  // the rest of the component...

}

相关问题