如何仅发送更新状态而不是整个对象

4jb9z9bj  于 2022-10-22  发布在  Java
关注(0)|答案(2)|浏览(142)

有人能就如何解决这个问题提出建议吗?
我有一张状态各异的表格。当用户更改任何表单输入并单击保存时,函数会将数据发送到后端。问题是,当我只想发送已更改的值/已更改的状态时,我将整个对象发送到后端。我该怎么做?
下面是一个例子:

const [streetName, setStreetName] = useState<string>('');
    const [zipCode, setZipCode] = useState<string>('');
    const [city, setCity] = useState<string>('');
    const [email, setEmail] = useState<string>('');
    const [phone, setPhone] = useState<string>('');

    const userData = {
        streetName,
        zipCode,
        city,
        email,
        phone
    };

    const saveDataOnClickHandler = (userData) => {
        updateUserMutation(userData);
    };
btqmn9zl

btqmn9zl1#

假设您以空字符串开始,并且这个初始状态(useState<string>('');),您可以在发送例如。

const userData = {
    streetName !== '' ? streetName : undefined,
    zipCode !== '' ? zipCode : undefined,
    city !== '' ? city : undefined,
    email !== '' ? email : undefined,
    phone !== '' ? phone : undefined
};

如果要发送从上次发送更改的字段,则需要保存这些值并将其与实际输入进行比较

streetName !== previouslySentStreetName ...
dsekswqp

dsekswqp2#

这取决于,因为您没有显示表单,所以我会假设输入的实际值与状态相关联。在这种情况下,我将向每个状态添加一个hasChanged属性,并在提交时发送一个新的userData对象:

const initValue = {
  value: '',
  hasChanged: false,
};

const [streetName, setStreetName] = useState(initValue);
const [zipCode, setZipCode] = useState(initValue);
const [city, setCity] = useState(initValue);
const [email, setEmail] = useState(initValue);
const [phone, setPhone] = useState(initValue);

const userData = {
  streetName,
  zipCode,
  city,
  email,
  phone,
};

const handleOnStreetChange = (event)=>{

    setStreetName({
        value: event.target.value,
        hasChanged: true,
      });
}
const handleOnZipCodeChange = (event)=>{

    setZipCode({
        value: event.target.value,
        hasChanged: true,
      });
}

const saveDataOnClickHandler = (userData) => {

    let freshUserData = {};

    Object.entries(userData).forEach((data) => {

      [key, value] = data;

      freshUserData = value.hasChanged
        ? { ...freshUserData, [key]: value }
        : freshUserData;
    });

  sendDataToBackend(freshUserData)
};

const submitForm = (e) => {
    e.preventDefault();
    saveDataOnClickHandler(userData)
  };

return (
  <>
    <form aria-label='form'>
      <input
        type='text'
        placeholder='Street Name'
        name='streetName'
        value={streetName}
        onChange={handleOnStreetChange}
      />
      <input
        type='text'
        placeholder='Zip Code'
        name='zipCode'
        value={zipCode}
        onChange={handleOnZipCodeChange}
      />

      <button type="submit" onClick={submitForm}>
        Send
      </button>
    </form>
  </>
);

相关问题