React 中动作的动态 URL 查询重定向

Dynamic URL query redirect on action in React

提问人:O-1998 提问时间:11/13/2023 最后编辑:isherwoodO-1998 更新时间:11/14/2023 访问量:62

问:

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

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

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

表单.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;

使用 SID 建议进行更新

import useForm from "./UseForm";
import { useState } from "react";

const FORM_ENDPOINT = "https://ml-backend.wonderfulsea-73c97836.uksouth.azurecontainerapps.io/net/image/prediction/"; // 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}`);
    }

    const { handleSubmit, status, message } = useForm({

      });

      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={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>
      {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 an image
          </button>
        </div>
      )}


        </form>
    );
};

export default Form;
javascript reactjs url 重定向 react-hooks

评论

1赞 sid 11/13/2023
你的意思是这个 document.getElementsByName(“image_link”).value 给出 null 吗?
0赞 O-1998 11/13/2023
是的。我将在上面澄清,但这给出了 null,因为我认为该值是在加载页面时获取的,而不是在输入表单上的值时动态获取的。
0赞 sid 11/13/2023
您在哪里管理表单输入?理想情况下应该处于一种状态,但我没有看到它

答:

1赞 sid 11/13/2023 #1

您可以侦听输入事件,并在输入元素失去焦点时更新您的状态。onBlurimage_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.target.value) {
            alert('please enter a valid value');
        }   
        setFormEndpoint(`${FORM_ENDPOINT}?image_link=${event.target.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;

应该以这种方式工作。

评论

0赞 O-1998 11/13/2023
嗨,sid,感谢您的回复。我已经尝试了这个解决方案,但是当我提交表单时,我似乎仍然得到一个未定义的值。我得到“端点?Image_link=未定义”。我将更新上面的代码。
0赞 sid 11/13/2023
检查handleOnBlur函数的更新代码,并查看它在日志中是否有有效值。
0赞 O-1998 11/13/2023
它似乎给了我一个警报,建议我需要输入一个有效的值,然后当我再次单击它时,在 url 中给了我一个未定义的image_link值
0赞 sid 11/14/2023
我的错,它的 event.target.value,肯定会起作用。
0赞 O-1998 11/14/2023
这确实很棒,谢谢!我将删除警报,因为它现在似乎每次都会触发,并且对于我的用例来说不是必需的。