我想将输入的值作为路由参数发送到服务器。我应该编写一个函数来编码这些值吗?我试图在没有任何库的情况下完成这个。
巧合的是,我误输入了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{}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
函数
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); };