首页 > 解决方案 > 如何在 API 获取有效负载之前格式化 React 表单提交

问题描述

我正在尝试提交一个将表单字段输入到 React 挂钩状态对象的表单。但是,应用程序中期望有效负载对象为某种格式的其他组件会访问有效负载对象。

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>
)

因此,formInput 对象有两个属性。但它们需要嵌套,如下所示:

//acceptable payload:
{cadet: [
  first-name: '',
  dept: ''
 ]
}

我尝试调用一个函数来使用新的状态对象包装它们,但它给了我一个未定义的模式属性错误:

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);

在上面的例子中,schema 的属性是 undefined、cadet 和 first-name。此外,为了在调用 API 之前设置 setFormattedInput 对象,我需要实例化具有它的函数,但由于 React 规则,调用 updateInput(); 当组件被渲染并且未定义时运行(有点像功能组件需要 componentDidUpdate() )。

这应该很常见——除非您从头开始构建应用程序,否则我们都需要在表单状态对象到达 API 之前重新格式化它们。有人知道怎么做吗?

为了提供一些上下文,NPM 包映射器做了需要做的事情,但它根本不起作用(https://www.npmjs.com/package/mapper)。

标签: reactjsformsreact-hookspayloadreact-functional-component

解决方案


我最终使用了一个自定义包装器并在此过程中修复了一些小的语法问题。在有效载荷中,

api.post('~/person/cadet', formInput);

我添加了

const formattedObj = formatted(formInput);
api.post('~/person/cadet', formattedObj);
console.log(formattedObj);

然后在同一个文件中我定义格式如下:

const formatted = (formInput) => {

  const payload = {cadet: [
    first-name: formInput.first-name,
    dept: formInput.person-dept
 ]}
return payload;
}

因此,formatted() 在状态对象中传递,payload 的行为有点像块变量,不需要调用它来作为 formatted() 返回的数据。

只是包装传递给 URL 路径的对象和 formatted() 中的一些语法的小步骤,基本工作流程是正确的。

我想分享,因为它需要几个强大的同事才能完成这项工作,并且应该在任何地方使用 React hooks 来教授它,以降低进入门槛。

感谢您的阅读,我希望这也适用于您!

PS-如果对象没有被保存,那是由于您从表单字段传递给对象的其他语法问题。此外,如果有一点点偏差,小的语法调整将使这个解决方案起作用。


推荐阅读