我需要你的幫助。我有一個我無法解決的問題。我是新來的。我正在嘗試向后端發送資訊。結果,我收到一個錯誤:Cannot read properties of undefined (reading 'preventDefault'). 我想問一下,我的錯誤是什么,我執行 POST 請求是否正確?謝謝
import React, { useEffect, useState } from 'react';
import axios from 'axios';
export let Form_Post = () => {
let [name, setName] = useState('');
let [price, setPrice] = useState('');
let [description, setDescription] = useState('');
let submitName = (e) => {
setName(e.target.value);
};
let submitPrice = (e) => {
setPrice(e.target.value);
};
let submitDescription = (e) => {
setDescription(e.target.value);
};
let sendLaptop = (event) => {
axios.post('http://localhost:8081/laptop', {
name: name,
price: price,
description: description,
});
event.preventDefault();
setName('');
setPrice('');
setDescription('');
};
useEffect(() => {
sendLaptop();
}, []);
return (
<form onSubmit={sendLaptop}>
<input type="text" value={name} onChange={submitName} />
<input type="text" value={price} onChange={submitPrice} />
<input type="text" value={description} onChange={submitDescription} />
<button onSubmit={sendLaptop}>Send</button>
</form>
);
};
uj5u.com熱心網友回復:
你叫sendLaptop你的useEffect鉤,以及對提交。當你這樣做時,沒有附加事件,因此event是未定義的,因此event.preventDefault也是未定義的。
uj5u.com熱心網友回復:
看起來問題與event.preventDefault()內部有關,sendLaptop因為它是從 2 個地方(useEffect&onClick處理程式)呼叫的。
從sendLaptop呼叫 get 的地方useEffect,沒有event傳遞變數。
您應該檢查事件是否通過,然后才呼叫它。
let sendLaptop = (event) => {
axios.post('http://localhost:8081/laptop', {
name: name,
price: price,
description: description,
});
if (event) {
event.preventDefault();
}
setName('');
setPrice('');
setDescription('');
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/368210.html
