首页  >  问答  >  正文

将输入值作为路由参数传递

我想将输入的值作为路由参数发送到服务器。我应该编写一个函数来编码这些值吗?我试图在没有任何库的情况下完成这个。

巧合的是,我误输入了localhost 8000,然后浏览器将localhost 3000的URL附加到8000上,然后才能使用set Search Params,并且我确实将这些值附加到了路由参数上,但服务器的URL显然不正确。

这是我的代码:

import axios from 'axios';
import React, { useState } from 'react';
import { useSearchParams } from 'react-router-dom';

const AddProductForm = ({ id }) => {
  let [searchParams, setSearchParams] = useSearchParams();
  const [input, setInput] = useState({
    title: '',
    price: '',
    rating: '',
    description: '',
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    setSearchParams(input)
    axios
      .put(`http://localhost:8080/api/v1/products/${id}?` + searchParams)
      .then((res) => console.log(res))
      .catch((err) => console.log(err));
  };

  const onChange = (e) => {
  //function to handle change of each input
   }

  return (
    <div className='container' >
      <form className='form' onSubmit={handleSubmit}>
        <div className='form_inputs'>
          <h1>Edit Product</h1>
          <div className='flex-column'>
            <label>Add new title</label>
            <input
              type='text'
              value={input.title}
              onChange={onChange}
              name='title'
              placeholder='Title'
            />
          </div>
          <div className='flex-column'>
            <label>Add new price</label>
            <input
              type='number'
              value={input.price}
              onChange={onChange}
              name='price'
              placeholder='Price'
            />
          </div>
         //All other inputs
        <button className='btn-block' type='submit'>
          Create
        </button>
      </form>
    </div>
  );
};

export default AddProductForm;

提交时,我只得到空对象URLSearchParams{}

P粉593649715P粉593649715377 天前523

全部回复(1)我来回复

  • P粉827121558

    P粉8271215582023-09-12 13:29:21

    函数 setSearchParams 的工作方式类似于函数 navigate,它会执行导航操作,但只会更新当前 URL 的搜索字符串。代码实际上并没有更新 searchParams 变量。

    您想要获取 input 状态并创建一个新的 URLSearchParams 对象。

    示例:

    const handleSubmit = (e) => {
      e.preventDefault();
      const searchParams = new URLSearchParams(input);
      axios
        .put(`http://localhost:8080/api/v1/products/${id}?${searchParams.toString()}`)
        .then(console.log)
        .catch(console.warn);
    };

    回复
    0
  • 取消回复