如何在react中更新表单时发送有限的字段



user.js

import React, { useState, useEffect } from 'react';
const Users = () => {
const [user, setUser] = useState({
name: '',
email: '',
phoneNumber: '',
role: '',
status: ''
});  ======>>>> I want to sent above fields only however while fetching user it fetchs extra fields that I don't want to send while  handle submit
const { name, email, phoneNumber, role, status } = user;
const handleChange = e => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const loadUser = async () => {
const res = await Axios.get(`http://localhost:3001/user/fetch/${id}`)
setUser(res.data.response.info)
};
useEffect(() => {
loadUser();
}, []);
const handleSubmit = async e => {
e.preventDefault();
await Axios.patch(`http://localhost:3001/user/${id}`, user)
};  ====>>> I want to sent limited user field here
return (
<form onSubmit={e => handleSubmit(e)} >
<div className="form-group">
<label htmlFor='name'>Name:</label>
<input type="text" name="name" id="name" className="form-control" value={name || ''} onChange={e => handleChange(e)} />
</div>
)
}

我正在更新用户,它运行良好,但我得到的错误是在用户状态下获取额外的字段。我如何处理发送的有限字段?在提交表单时处理提交,就像我不想将额外的字段发送到后端一样。我只想要状态为的字段

为什么不设置要设置的字段,而忽略其余字段呢?

const loadUser = async () => {
const res = await Axios.get(`http://localhost:3001/user/fetch/${id}`);
const _user = res.data.response.info;
setUser({
email: _user.email,
//// rest,
})
};

或者在修补之前只允许您想要的密钥

function allowKeys(obj, keysAllowed) {
const newObj = {}
for (const key in obj) {
if (keysAllowed.includes[key]) {
newObj[key] = obj[key]
}
}
return newObj
}
// at the time of patching
const toBePatchedUser = allowKeys(user, ["email"... /** only allowed keys here */])

相关内容

  • 没有找到相关文章

最新更新