【发布时间】:2021-03-02 05:33:33
【问题描述】:
我正在尝试从我的反应前端向我的 NodeJS API 发送 PATCH 请求。我想要一种情况,如果您单击编辑按钮,初始名称 price 会出现在输入中以进行必要的编辑。然后编辑后,您可以对其进行更新。显示初始数据工作正常,但保存它不起作用。我收到错误消息:“警告:无法对未安装的组件执行 React 状态更新。这是一个无操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 useEffect 中的所有订阅和异步任务清理功能。” 我查看了清理功能,但无法取得进展。 下面是我的代码。
const EditUserForm = () => {
const history = useHistory();
const match = useRouteMatch();
let routeId = match.params.id;
console.log(routeId);
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [item, setItem] = useState({});
const [name, setName] = useState();
const [price, setPrice] = useState();
const handleInputChange = (e) => {
console.log(e.target.value)
const { name, value } = e.target;
setItem({ ...item, [name]: value});
};
const handleSubmit = (e) => {
e.preventDefault();
updateProduct();
history.push('/');
}
const updateProduct = () => {
fetch(`/addproducts/${routeId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: item.name,
price: item.price
}),
})
.then((res) => res.json())
.then((result) => setItem(result))
.catch((err) => console.log('error: ', err))
}
useEffect(() => {
fetch(`/products/${routeId}`, requestOptions)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setName(result.product.name);
setPrice(result.product.price);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, []);
return (
<form onSubmit={handleSubmit} >
<label>Name</label>
<input
type="text"
name="name"
defaultValue={name}
onChange={handleInputChange}
/>
<label>Price</label>
<input
type="text"
name="price"
defaultValue={price}
onChange={handleInputChange}
/>
<button type="submit">Update</button>
<button>
Cancel
</button>
</form>
)
}
export default EditUserForm
【问题讨论】:
-
你的 api 在 postman 中运行良好吗?
-
你试过其他方法吗?即 GET、POST
-
API 在 Postman 中运行良好。 GET 和 POST 请求也可以正常工作。 @FirstArachne
标签: node.js reactjs api react-hooks