在React和Material UI中使用Axios进行更新请求



我对React很陌生,我所做的唯一CRUD功能一直在MVC.net中,所以我在这里很迷路,我发现的教程似乎都不是我所遇到的情况……也许我只是误解了他们。我从最初的问题中得到的提示有所帮助,但我仍然没有得到它的工作,所以希望现在我有足够的信息来帮助其他人帮助我。我没有包括所有的输入字段,因为它们像15,这只是多余的。

我正在使用这个onClick事件拉起模态:

onClick={()=> {handleEditModal(item)}}

modalFunctions.js

// Modal Functionality
export function ModalFunctions() {
const [selectedRecord, setSelectedRecord] = useState([]);
const [openModal, setOpenModal] = useState(false);
const handleEditModal = item =>{
setOpenModal(true)
setSelectedRecord(item)
} 
return {
selectedRecord,
setSelectedRecord,
openModal,
setOpenModal,
handleEditModal,
handleDetailModal
}
}
// Form Functionality
export function FormFunctions(validateOnChange = false, validate) {
const [values, setValues] = useState('');
const [errors, setErrors] = useState({});

const handleInputChange = e => {
const { name, value } = e.target
setValues({
...values,
[name]: value
})
if (validateOnChange)
validate({ [name]: value })
}
return {errors, handleInputChange, setErrors, setValues, values}
}

DataTable.js

// Imported Modal Functions
const {
selectedRecord,
openModal,
setOpenModal,
handleEditModal,
handleDetailModal
} = ModalFunctions();
const baseURL = 'http://localhost:8080/api/tanks'; 
// Fetch Data
useEffect(() => {
const fetchData = async () =>{
setLoading(true);
try {
const {data: response} = await axios.get(baseURL);
setTableData(response);
} catch (error) {
console.error(error.message);
}
setLoading(false);
};
fetchData();
}, [baseURL, setTableData, setLoading]);

// The Modal
return(
<Modal
title={ "Editing: " + (selectedRecord.tankName) }
openModal={openModal}
setOpenModal={setOpenModal}
>
<TankEdit
selectedRecord={selectedRecord}
setOpenModal={setOpenModal}
openModal={openModal} 
/>
</Modal>
)

TankEdit.js

export function TankEdit(props) {
const { baseURL, openModal, selectedRecord, setOpenModal, setTableData } = props;
const validate = (fieldValues = item) => {
let temp = { ...errors }
if ('tankName' in fieldValues)
temp.tankName = fieldValues.tankName ? "" : "This field is required."
setErrors({
...temp
})
if (fieldValues === values)
return Object.values(temp).every(x => x === " ")
}
const {
values,
setValues,
errors,
setErrors,
handleInputChange,
} = FormFunctions(true, validate);
useEffect(() => {
if (selectedRecord !== null)
setValues({
...selectedRecord
})
}, [selectedRecord, setValues])

function editRecord() {
axios.put(`${baseURL}`, {
title: "Success",
body: "The record had been successfully updated"
}).then ((response) => {setTableData(response.data);})
}
const handleSubmit = e => {
e.preventDefault()
if (validate()) {
editRecord(values);
}
setOpenModal(false)
}
const item = values; // used for easier referencing (matches table item)
return (
<Form onSubmit={handleSubmit} open={openModal}> 
<Grid>
<Controls.Input
name="tankName"
label="Tank Name"
value={item.tankName}
onChange={handleInputChange}
error={errors.tankName}
/>
</Grid>
<Grid>
<Controls.Button
type="submit"
text="Submit"
/>
<Controls.Button
text="Cancel" 
color="default"
onClick={()=>{setOpenModal(false)}}
/>
</Grid>
</Form>
)
}

Input.js

export default function Input(props) {
const { error=null, label, name, onChange, value, ...other } = props;
return (
<TextField
variant="outlined"
label={label}
name={name}
value={value}
defaultValue=''
onChange={onChange}
{...other}
{...(error && {error:true,helperText:error})}
/>
)
}

我的公司只想要一个读取和更新功能,因为创建和删除将以另一种方式处理,所以这是我最后的挂起。我想我很接近了,但是我还缺少一些东西。

谁能给我指个正确的方向?谢谢! !

如果你想写一个更新请求,你可以使用axios。Put将数据发送到后端。

在handlessubmit函数中:

let response = await axios.put('http://-------/api/tanks', { name: 'tank' });

(第二个参数是一个需要包含所有表单数据字段的对象)

还要确保在handlessubmit函数中调用e.p preventdefault(),这样你就不会不小心导航到其他地方。

然后你将更新你的数据库或使用你的后端。

更新你应该使用putpatch方法并且您应该在请求url中发送您要更新的项目的id。我在这里插入2个例子。这是put:

const res = await axios.put('/api/article/123', {
title: 'Making PUT Requests with Axios',
status: 'published'
});

这是补丁:

const res = await axios.patch('/api/article/123', {
title: 'Making PUT Requests with Axios',
status: 'published'
});

最新更新