简体   繁体   English

如何仅传递在 POST 请求正文中更改的那些值

[英]how to pass only those values which changed in POST request body

I have multiple state variables, that contains data entered in a form by the user.我有多个 state 变量,其中包含用户在表单中输入的数据。 Since this form is only meant to update the existing values, I have to pass in only those values that have changed from its initial value (the one returned from the GET request).由于此表单仅用于更新现有值,因此我必须仅传递那些已从其初始值(从 GET 请求返回的值)更改的值。

State: State:

const [name, setName] = useState(props.user?.name ?? null);
const [lang, setLang] = useState(props.user?.lang ?? null);
const [enableChecks, setEnableChecks] = useState(props.user?.checkEnabled ?? false)

In the event that the user only changed the name, how can I pass in only name in the request body?如果用户只更改了名称,我如何在请求正文中仅传递名称?

What I have tried: I have the user props, so I have multiple if statements that check if the props matches the state. If it doesn't, then I add it to the request payload.我尝试了什么:我有用户道具,所以我有多个 if 语句来检查道具是否与 state 匹配。如果不匹配,那么我将其添加到请求负载中。 This works, but when there's a lot of state, there will be a lot of if statements, which isn't nice to look at.这个可以,但是当state很多的时候,if语句会很多,不好看。

Is there a better way to do this?有一个更好的方法吗?

You can keep your state in an object, and then only update field state when the updatedUser and user state values are different.您可以将您的 state 保留在 object 中,然后仅在更新的用户和user state 值不同时更新字段updatedUser

 //use `import` in your real component instead //import { useState } from 'react'; const { useState } = React; //fake your user prop const userProp = { name: "Name", lang: "English", } function App(props) { const [user, setUser] = useState(props.user); const [updatedUser, setUpdatedUser] = useState({}); const handleChange = (e) => { const newlyUpdatedUser = {...updatedUser, } if(props.user[e.target.name] === e.target.value) { delete newlyUpdatedUser[e.target.name] } else { newlyUpdatedUser[e.target.name] = e.target.value } setUpdatedUser(newlyUpdatedUser); setUser({...user, [e.target.name]: e.target.value }) }; console.log(updatedUser) return ( <React.Fragment> <label> Name: <input value={user.name} name="name" onChange={handleChange} /> </label> <label> Lang: <input value={user.lang} name="lang" onChange={handleChange} /> </label> </React.Fragment> ); } ReactDOM.render(<App user={userProp} />, document.getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script> <div id="root"></div>

Instead of having multiple state variables, you can have a single state variable like您可以拥有一个 state 变量,而不是拥有多个 state 变量,例如

const [state, setState] = useState(props.user)

and then change handler should look like然后更改处理程序应该看起来像

const handleChange = (e) => {
    setState({
      ...state,
      [e.target.name]: e.target.value,
    });
  };

finally, when submitting the form you can make your body data for post request like最后,在提交表单时,您可以为发布请求制作您的身体数据,例如

const handleSubmit = () => {
  const requestData = {}  

  for (const [key, value] of Object.entries(state)){
    if(props.user[key] !== value) {
      requestData[key] = value
    }
  }

  axios.post('some api url', responseData)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何仅捕获用户更改值的多行中的那些列? - How do I capture only those columns in multiple rows in which user has changed values? d3如何在邮件请求中正确传递请求正文? - d3 how to properly pass request body in a post request? 如何在axios post请求中传递formData和body参数 - How to pass formData and body parameters in axios post request 如何在请求正文中传递变量? - How to pass variable in request body? 如何发送带有json正文的帖子请求,其中正文仅包含一个字符串而不是键值对? - How do I send post request with json body where the body only contains a string not a key value pair? 如何在XMLhttp Post请求中传递多个文件值 - How to Pass multiple file values in XMLhttp Post request jQuery仅循环其中具有值的那些输入 - Jquery loop through only those inputs which has values in it 如何通过NodeJS中的POST http.request传递响应参数(包括正文) - How to pass response paramaters including body from POST http.request in NodeJS 如何将一组数据从客户端传递到 axios 发布请求的 req.body - How to pass an array of data from the client side to req.body of an axios post request 如何使用 Datatable 以 POST 类型传递请求正文数据以使用 Javascript 进行服务器端分页 - How to pass request body data in type POST using Datatable for Serverside pagination using Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM