我有一个成功的页面,这是在成功付款后显示。URL有一个查询参数。加载后,我希望将查询参数发送到我的api端点。我的问题是,第一个POST请求是空的(router.query = {})。当每次触发useEffect时(这意味着它发送多个POST请求),第二个POST请求包含查询参数。我怎么做才能让它只在有一个实际查询参数的时候发布,这样它就不会发送空的POST请求了。
这是我的代码:
const Success = () => {
const { state, dispatch } = useContext(DataContext);
const router = useRouter()
useEffect(async ()=>{
await postData('order/decreaseInStock', router.query)
},[]) // when i remove the [] the first POST req is still empty but the second and those after contain the correct param
return (
<div className='flex flex-col h-screen items-center'>
<div className='flex mt-60 flex-col items-center p-12 py-16 bg-gray-100 rounded-md shadow-xl'>
<h1 className='text-green-400 text-5xl font-extrabold'>
Takk for din bestilling!
</h1>
<Link href='/'>
<div className='flex items-center mt-9 cursor-pointer'>
<ArrowLeft />
<a>Tilbake</a>
</div>
</Link>
</div>
</div>
);
};发布于 2021-05-10 03:42:20
由于您只想在查询参数中有内容时进行POST,因此您可以这样做。
useEffect(() => {
// This will trigger your api call if any query params exists.
// This can be more finegrained to only trigger if all your params are present.
if (Object.keys(router.query).length) {
postData('order/decreaseInStock', router.query)
}
}, [router.query])https://stackoverflow.com/questions/67461666
复制相似问题