在React JS中创建表单后立即提交表单

时间:2019-12-24 07:25:07

标签: javascript reactjs jsx react-hooks

我有一个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()之前创建表单?

2 个答案:

答案 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)

检出此沙盒https://codesandbox.io/s/optimistic-vaughan-sb8hr

它按预期工作