React 中的动态 url 查询重定向操作

问题描述 投票:0回答:1

我正在尝试对 React 中的表单查询使用重定向。我尝试了很多方法,但似乎无法使其发挥作用。总的来说,我对前端开发还是个新手,所以看起来相当微不足道的事情给我带来了一些痛苦。

我当前的应用程序的要点是,该操作从表单输入中获取空值,因为在运行时创建操作时该值为空。输入是元素“image_link”的值。

设置它以便将传递的 URL 包含在查询参数中的最佳方法是什么。我将在下面附上 Form.js 和 UseForm.js。

FORM.js

import useForm from "./UseForm";

const FORM_ENDPOINT = "https://ENDPOINT"; // TODO - update to the correct endpoint

const Form = () => {
  const additionalData = {
    sent: new Date().toISOString(),
  };

  const { handleSubmit, status, message } = useForm({
    additionalData,
  });

  if (status === "success") {
    return (
      <>
        <div className="text-2xl">Thank you!</div>
        <div className="text-md">{message}</div>
      </>
    );
  }

  if (status === "error") {
    return (
      <>
        <div className="text-2xl">Something bad happened!</div>
        <div className="text-md">{message}</div>
      </>
    );
  }

  return (
    <form  
      action={FORM_ENDPOINT+"?image_link="+document.getElementsByName("image_link").value}
      onSubmit={handleSubmit}
      method="POST"
    >
      <div className="pt-0 mb-3">
        <input
          type="text"
          placeholder="Image Link"
          name="image_link"
          className="focus:outline-none focus:ring relative w-full px-3 py-3 text-sm text-gray-600 placeholder-gray-400 bg-white border-0 rounded shadow outline-none"
          required
        />
      </div>
      {status !== "loading" && (
        <div className="pt-0 mb-3">
          <button
            className="active:bg-blue-600 hover:shadow-lg focus:outline-none px-6 py-3 mb-1 mr-1 text-sm font-bold text-white uppercase transition-all duration-150 ease-linear bg-blue-500 rounded shadow outline-none"
            type="submit"
          >
            Submit Image
          </button>
        </div>
      )}
    </form>
  );
};

export default Form;

UseForm.js

import { useState } from "react";

async function useForm({ additionalData }) {
  const [status, setStatus] = useState('');
  const [message, setMessage] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    setStatus('loading');
    setMessage('');

    const finalFormEndpoint = e.target.action;
    const data = Array.from(e.target.elements)
      .filter((input) => input.name)
      .reduce((obj, input) => Object.assign(obj, { [input.image_link]: input.value }), {});

    if (additionalData) {
      Object.assign(data, additionalData);
    }

    fetch(finalFormEndpoint, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
      .then((response) => {
        if (response.status !== 200) {
          throw new Error(response.statusText);
        }

        return response.json();
      })
      .then((response) => {
        setMessage("The result is: " + response.body);
        setStatus('success');
      })
      .catch((err) => {
        setMessage(err.toString());
        setStatus('error');
      });
  };

  return { handleSubmit, status, message };
}

export default useForm;
javascript reactjs url redirect react-hooks
1个回答
0
投票

您可以监听

onBlur
输入的
image_link
事件,并在输入元素失去焦点时更新您的状态。

const FORM_ENDPOINT = "https://ENDPOINT"; // TODO - update to the correct endpoint

const Form = () => {
    // add this to your Form component before return ()
    const [formEndpoint, setFormEndpoint] = useState(FORM_ENDPOINT);

    const handleOnBlur = (event) => {
        if(!event?.data?.value) {
            alert('please enter a valid value');
        }   
        setFormEndpoint(`${FORM_ENDPOINT}?image_link=${event?.data?.value}`);
    }

    return (
        <form  
        action={formEndpoint}
        onSubmit={handleSubmit}
        method="POST"
        >
            <div className="pt-0 mb-3">
                <input
                type="text"
                placeholder="Image Link"
                name="image_link"
                onBlur={handleOnBlur}
                className="focus:outline-none focus:ring relative w-full px-3 py-3 text-sm text-gray-600 placeholder-gray-400 bg-white border-0 rounded shadow outline-none"
                required
                />
            </div>
        </form>
    );
};

export default Form;

应该这样工作。

© www.soinside.com 2019 - 2024. All rights reserved.