我有一个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
</>
) : (
<></>
)}
<></>
);
};
submit()抛出Uncaught TypeError: Cannot read property 'submit' of null
如何确保在调用Submit()之前创建表单?
答案 0 :(得分:1)
您无法在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>
</>
);
};
答案 1 :(得分:0)