如何在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);

在上面的示例中,架构的属性为undefined,cadet和first-name。 另外,为了在调用API之前设置setformattedInput对象,我需要实例化具有该对象的函数,但是由于有React规则,因此调用updateInput();。在呈现组件且未定义组件时运行(有点像需要功能组件的componentDidUpdate())。

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

要提供一些背景信息,NPM软件包映射器会执行所需的操作,但它根本不起作用(https://www.npmjs.com/package/mapper)。

yanglibaoqi 回答:如何在API获得有效载荷之前格式化React表单提交

我最终使用了自定义包装器,并在此过程中解决了较小的语法问题。在有效载荷中,

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()被传递到状态对象中,并且有效负载的行为类似于块变量,无需调用它即可将其作为formatted()返回的数据。

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

我想分享一下,因为这项工作花了一些强大的同事的头脑,应该在各处使用React钩子来教它,以降低进入门槛。

感谢阅读,我希望它也对您有用!

P.S。-如果未保存对象,则归因于从表单字段传递到对象中的其他语法问题。此外,如果有一点点改动,只需进行较小的语法调整即可使该解决方案生效。

本文链接:https://www.f2er.com/2873752.html

大家都在问