如何在有效负载可用时首次发出 POST 请求?

时间:2021-05-09 19:35:00

标签: javascript reactjs next.js

我有一个成功付款后显示的成功页面。 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>
    );
};

1 个答案:

答案 0 :(得分:0)

看到您只想在查询参数中有内容时发布,您可以执行类似的操作。

UserModel.ts