Reactjs 如何在API获得有效负载之前格式化React表单提交
我正在尝试提交一个表单,该表单将表单字段输入到React钩子状态对象中。但是,有效负载对象由应用程序中的其他组件访问,这些组件期望有效负载对象为特定格式Reactjs 如何在API获得有效负载之前格式化React表单提交,reactjs,forms,react-hooks,payload,react-functional-component,Reactjs,Forms,React Hooks,Payload,React Functional Component,我正在尝试提交一个表单,该表单将表单字段输入到React钩子状态对象中。但是,有效负载对象由应用程序中的其他组件访问,这些组件期望有效负载对象为特定格式 const [formInput, setFormInput] = useState(); const onChange = event => { event.target.name = event.target.value; } return ( <form onSubmit="props.onSubmit"> &
const [formInput, setFormInput] = useState();
const onChange = event => {
event.target.name = event.target.value;
}
return (
<form onSubmit="props.onSubmit">
<label>First Name</label>
<input value="formInput.first-name" name="first-name" onChange={onChange}></input>
<input value="formInput.person-dept" name="person-dept" onChange={onChange}></input>
<button type="submit">Add a cadet</button>
</form>
)
我尝试调用一个函数,使用一个新的状态对象包装它们,但它为schema属性提供了一个未定义的错误:
const schema = () => {
cadet: [
first-name: '',
dept: ''
]
}
const [formattedInput, setFormattedInput] = useState(schema);
const updateInput = () => {
setFormattedInput(
cadet: {
{first-name: {formInput.first-name} || null},
{dept: {formInput.person-dept} || null}
}
)
}
updateInput();
api.post('~/person/cadet', updateInput);
在上面的示例中,模式的属性是未定义的、cadet和first name。
另外,为了在调用API之前设置setFormattedInput对象,我需要实例化拥有它的函数,但是由于React规则,调用updateInput();在呈现组件且组件未定义时运行(有点像功能组件需要componentDidUpdate()
这应该是非常常见的-除非您从头开始构建应用程序,否则我们都需要在表单状态对象到达API之前重新格式化它们。有人知道怎么做吗
为了提供一些上下文,NPM包映射器做了需要做的事情,但它根本不起作用()。我最终使用了一个自定义包装器,并解决了一些小的语法问题。在有效载荷中
api.post('~/person/cadet', formInput);
我补充说
const formattedObj = formatted(formInput);
api.post('~/person/cadet', formattedObj);
console.log(formattedObj);
然后在同一个文件中,我定义了如下格式:
//acceptable payload:
{cadet: [
first-name: '',
dept: ''
]
}
const formatted = (formInput) => {
const payload = {cadet: [
first-name: formInput.first-name,
dept: formInput.person-dept
]}
return payload;
}
因此,formatted()在state对象中传递,负载的行为有点像块变量,不需要调用它作为formatted()返回的数据
只需包装传递到URL路径的对象的一小步,以及formatted()中的一些语法,基本工作流是正确的
我想与大家分享,因为这需要几个强大的同事的头脑才能完成,而且应该在每个地方使用React挂钩来降低进入门槛
谢谢你的阅读,我希望这对你也有用
注意:如果对象未保存,则是由于从表单字段传递到对象中的其他语法问题造成的。此外,如果有点不对劲,轻微的语法调整将使此解决方案起作用