【发布时间】:2020-02-21 01:38:40
【问题描述】:
我正在从表单的三个独立填充的小节中制作一个对象。它们是独立填充的,因为数据来自三个不同的来源:
1) 名称和地址的后端 api 2)电话号码的第三方api 3) 用户在表单中的其他字段上执行 onChange
我注意到的是,如果我提交表单时 onChange 是最后一个执行的函数,即如果输入注释或更新电子邮件地址,那么其他两个元素会删除一些数据,特别是每个源的第一个字段.
我通过创建一个基本上运行表单控制操作(基本上重置电话号码)的效果来解决这个问题,这样做可以解决问题,但显然我不想不必依赖 useState 方法并调用它不是为了解决我不明白的问题。这是一些代码。
谢谢!
const leadContext = useContext(LeadContext);
const { clearLiens, lien, setLien, letCall, number, clearNumber, addLead, postLogics } = leadContext;
useEffect(() => {
if (lien !== null) {
setRecord(lien);
}else {
setRecord({
name: '',
address:'',
city:'',
state:'',
zip:'',
plaintiff:'',
amount:''
});
}
}, [lien, leadContext]);
useEffect (()=>{
if(number !== null){
setCall({phone:number});
}else {
setCall({phone:''});
}
},[number, leadContext]);
const [ record, setRecord ] = useState({
name: '',
address:'',
city:'',
state:'',
zip:'',
plaintiff:'',
amount:'',
lienid:''
});
const [ call, setCall ] = useState({
phone: ''});
const [ open, setOpen ] = useState({
email:'',
lexId:'',
compliant:'filed',
filingStatus:'married',
cpa: 'cpa',
ssn:'',
noteText:''
});
const onChange = e => {
setRecord({...name, address, city, state, zip, plaintiff, amount, [e.target.name]: e.target.value });
setCall({...phone, [e.target.name]: e.target.value });
setOpen({...email, lexId, compliant, filingStatus, cpa, ssn, noteText, [e.target.name]: e.target.value});
}
const { name, address, city, state, zip, plaintiff, amount, lienid } = record
const { phone } = call
const { email, lexId, compliant, filingStatus, cpa, ssn, noteText } = open
const lead = {phone, name, address, city, state, zip, plaintiff, amount, lienid, email, lexId, compliant, filingStatus, cpa, ssn, noteText }
const clearLead = () => {
clearNumber();
setLien('');
setRecord({
name: '',
address:'',
city:'',
state:'',
zip:'',
plaintiff:'',
amount:'',
});
setCall({
phone: ''});
setOpen({
email:'',
lexId:'',
compliant:'filed',
filingStatus:'m',
cpa: 'cpa',
noteText:'',
ssn:''
});
}
const onSubmit = e => {
e.preventDefault();
addLead(lead);
clearAll();
};
const clearAll = () => {
clearLiens();
clearLead();
};
const onClick = e => {
letCall(number);
}
letCall(number) 是我在表单字段之一上基本上调用设置状态的热修复。我也不能将它堆叠到我的提交中,所以它必须作为一个单独的函数来完成。
const addLead = async lead => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const { phone, name, address, city, state, zip, plaintiff, amount, lienid, email, lexId, compliant, filingStatus, cpa, ssn, noteText } = lead
const noteId = uuidv4();
const notes = [{ id : noteId,
note : noteText,
notePostedBy: ''
}]
const steve = {phone, name, address, city, state, zip, plaintiff, amount, lienid, email, lexId, compliant, filingStatus, cpa, ssn, notes }
console.log(lead,'1');
console.log(steve,'1');
const res = await axios.post('/api/leads/', steve, config);
dispatch({
type: POST_LEAD,
payload: res.data
});
};
【问题讨论】:
标签: reactjs react-hooks