React Hook 在函数调用中更新状态变量

React Hook to update State Variable in a Function call

所以我有一个挂钩,它在更改时获取输入字段值并设置变量。

更新

HooksLib.js

 import { useState } from "react";

export function useFormFields(initialState) {
  const [fields, setValues] = useState(initialState);

  return [
    fields,
    function(e, name = '') {
      if (e instanceof Object && e.target instanceof Object) {
        // Safe to assume it was an event passed in
        setValues({ ...fields, [e.target.id]: e.target.value });
      } else {
        // Assume the value was passed in directly
        setValues({ ...fields, [name]: e });
      }
    }
  ];
}

我想使用同一个钩子在函数调用中设置一个变量。我该怎么做?

如何在函数调用中添加 event.target.id 和 event.target.value?

我想将其添加到的功能如下....特别是 ///then update a variable called "fields.customerId" as the value of "customer" 所在的位置。

handleSignUpSubmit 异步函数

const [fields, handleFieldChange] = useFormFields({
    name: "",
    email: "",
    customerId: "null"
  });

async function handleSignUpSubmit(event) {
    event.preventDefault();



    setIsLoading(true);

    try {
      const customer = await createCustomer({ email: fields.email, name: fields.name});
      ///then update a variable called "fields.customerId" as the value of "customer"
    } catch (e) {
      alert(e.message);
      setIsLoading(false);
    }
}

感谢您的帮助!

如果我没有正确理解你的问题,我会看到两个选项。

您可以制作一个类似于事件的对象并将其传入:

const myEvent = {
  target: {
    id: 'test',
    value: 'test2'
  }
}

...

handleFieldChange(myEvent);

或者另一种方法是在自定义挂钩中包含一个检查,以允许使用键名作为可选参数传入事件或普通值:

function(e, name = '') {
  if (e instanceof Object && e.target instanceof Object) {
    // Safe to assume it was an event passed in
    setValues({ ...fields, [e.target.id]: e.target.value });
  } else {
    // Assume the value was passed in directly
    setValues({ ...fields, [name]: e });
  }
}

然后这样称呼它:

const customer = await createCustomer({ email: fields.email, name: fields.name});
handleFieldChange(customer, 'customerId');