简体   繁体   English

如何在由 onSubmit 调用的函数内使用状态?

[英]How to use state inside a function called by onSubmit?

I'm having an issue using state inside a function that is called by redux-form's Form component's onSubmit.我在使用由 redux-form 的 Form 组件的 onSubmit 调用的函数内的 state 时遇到问题。

I need to access a given piece of state, tabs and currentTab.我需要访问给定的状态、选项卡和 currentTab。 The first is an array of tabs, the second is an indicator to which tab the user currently is.第一个是选项卡数组,第二个是指示用户当前所在的选项卡。

I've tried using a click event to handle the submission and it all works fine.我试过使用点击事件来处理提交,一切正常。

Passing state as a parameter does not work.将状态作为参数传递不起作用。 eg例如

<Form onSubmit={() => submit(currentTab, tabs.length)}>
  ...
</Form>

it still uses the default state of 0.它仍然使用默认状态 0。

I've also tried using the handleSubmit prop given to decorated components but got no luck with that.我也试过使用给装饰组件的 handleSubmit 道具,但没有成功。

The issue is that the state inside the function is not up to date with the actual state when the submit event occurs.问题是当提交事件发生时,函数内部的状态与实际状态不一致。

const [tabs, setTabs] = useState([])
const [currentTab, setCurrentTab] = useState(0)
console.log('outside', tabs.length); // outside 2
const submit = () => { 
  console.log('inside', tabs.length); /* inside 0  <- still the 
  default value provided to useState */
  if (tabs.length == currentTab + 1) {
    props.onSubmit();
  } else {
    handleNextTab();
  }
};
<Form onSubmit={submit}>
  ...
</Form>

Since the tabs are dynamic and can vary in length i want to be able to compare the tabs.length to the currentTab to know whether or not the user is in the last tab to trigger different actions depending on the result.由于选项卡是动态的并且长度可以变化,我希望能够将 tabs.length 与 currentTab 进行比较,以了解用户是否在最后一个选项卡中以根据结果触发不同的操作。

If the state is true at the time of rendering the Form , you could curry the onSubmit handler, and pass the state to the handler.如果在呈现Form时状态为真,您可以咖喱onSubmit处理程序,并将状态传递给处理程序。

I am thinking:我在想:

<Form onSubmit={handleSubmit(tabs, currentTab)}>
  ...
</Form>

And:和:

const handleSubmit = (tabs, currentTab) => {
    return () => {
        // Do something with `tabs`, and `currentTab` here
    };
};

See also (related): https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback另见(相关): https : //reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changed-value-from-usecallback

您需要将选项卡作为参数传递给您的提交函数。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM