我有一个ID为redirectForm
的表单,我需要在DOM中创建后立即自动提交。我正在使用 React Hooks。我当前的代码不起作用。
const Pay = () => {
const [payToken, setPayToken] = useState('');
const generatePaymentToken = () => {
fetch('https://somepostdomain.com/v1/GenerateChecksum', {
method: 'post',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
orderId: '1',
orderAmount: amt,
})
})
.then(res => res.json())
.then(res => {
setPayToken(res.checksumValue);
})
};
useEffect(() => {
const form = document.getElementById('redirectForm');//Not working
//console.log("form", form);
}, []);
return (
<button onClick={generatePaymentToken}>Pay</button>
{payToken !== '' ? (
<>
<form
id="redirectForm"
method="post"
action="https://test.somedomain.com/checkout/post/submit"
>
<input type="hidden" name="appId" value="<YOUR_APPID_HERE>" />
<input type="hidden" name="orderId" value="order00001" />
<input type="hidden" name="signature" value={payToken} />
</form>
{document.getElementById("redirectForm").submit()}//This throws Uncaught TypeError: Cannot read property 'submit' of null
</>
) : (
<></>
)}
<></>
);
};
提交(( 抛出Uncaught TypeError: Cannot read property 'submit' of null
如何确保在调用 submit(( 之前创建表单?
您不能访问语句return
DOM 元素。在基于类的组件中,我们使用componentDidMount
方法来访问 DOM 元素。在功能组件中,您可以使用Effect
钩子。
import React, { useEffect } from "react";
const Pay = () => {
useEffect(() => {
const form = document.getElementById("redirectForm");
console.log("form", form);
// document.getElementById("redirectForm").submit();
}, []);
return (
<>
<form
id="redirectForm"
method="post"
action="https://test.somedomain.com/checkout/post/submit"
>
<input type="hidden" name="appId" value="<YOUR_APPID_HERE>" />
<input type="hidden" name="orderId" value="order00001" />
</form>
</>
);
};
查看此沙盒 https://codesandbox.io/s/optimistic-vaughan-sb8hr
它按预期工作