英文:
After clicking on button fetch method is called endlessly
问题
I want to use a modal within a 'use client' page.tsx. I use this example for this: link. However, if I click on the button, my fetch call is set in an endless loop and called indefinitely, the app hangs. What's the problem here?
I use Next in the 13.4.3 Version.
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>;
}
After clicking on the button:
英文:
I want to use a modal within a 'use client' page.tsx. I use this example for this: https://www.creative-tim.com/learning-lab/tailwind-starter-kit/documentation/react/modals/regular. However, if I click on the button, my fecth call is set in an endless loop and called indefinitely, the app hangs. What's the problem here?
I use Next in the 13.4.3 Version.
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>
...
}
after click on button:
答案1
得分: 0
你在每次组件渲染时都进行了一次AJAX请求。这可能不是你想要的。
相反,使用useEffect
在第一次渲染时进行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);
})();
}, []);
// 组件的其余部分...
}
英文:
You're making an AJAX request on every render of the component. That's probably not what you want.
Instead, use useEffect
to make the AJAX request on the first render (or any time a given set of dependencies changes, which doesn't appear to be the case here) and update state with the result. For example:
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...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论