[英]Why is it requiring two clicks to execute state change in react?
I'm having a real hard time trying to wait for state change.我真的很难等待状态更改。 I'm using react hooks and context.我正在使用反应钩子和上下文。
Basically, I have a custom dropdown, no form elements used here.基本上,我有一个自定义下拉列表,这里没有使用表单元素。 On click, it will run a function to change the state of two parameters:单击时,它将运行一个函数来更改两个参数的状态:
// IdeaFilters.js
const organizationContext = useOrganization();
const { organization, filterIdeas, ideas, loading } = organizationContext;
const [filter, setFilter] = useState({
statusId: "",
orderBy: "voteCount"
});
// Build the parameters object to send to filterIdeas
const onClick = data => {
setFilter({ ...filter, ...data });
filterIdeas(filter);
};
So the onClick
is attached to a dropdown in the render method:因此onClick
附加到渲染方法中的下拉列表:
First dropdown:
<Dropdown.Item onClick={() => onClick({ orderBy: "popularityScore" })}>Popularity</Dropdown.Item>
Second dropdown:
<Dropdown.Item key={status.id} onClick={() => onClick({ statusId: status.id })}>
{status.name}
</Dropdown.Item>
fetchIdeas()
basically runs a function available in my context, that builds those parameters for my axios request. fetchIdeas()
基本上运行一个在我的上下文中可用的函数,它为我的 axios 请求构建这些参数。 Every time I click, it requires two clicks for the idea to run.每次单击时,都需要单击两次才能运行该想法。 Sometimes it runs as expected, but most of the time it takes two clicks.有时它会按预期运行,但大多数时候需要单击两次。
Any reason why I'm running into this issue?我遇到这个问题的任何原因?
Any help will be really appreciated!任何帮助将不胜感激!
Try this尝试这个
const onClick = data => {
const newFilter = { ...filter, ...data }
setFilter(newFilter)
filterIdeas(newFilter)
}
Instead of代替
const onClick = data => {
setFilter({ ...filter, ...data })
filterIdeas(filter)
}
In React setState
is asynchronous , I guess that was your problem.在 React setState
是异步的,我想那是你的问题。 Try the code above, if it works and you don't fully understand, please comment below I'll edit the answer to explain more clearly.尝试上面的代码,如果它有效并且您不完全理解,请在下面发表评论,我将编辑答案以更清楚地解释。 Read my other answer here (yet in the case your problem is asynchronous setState
) about how to handle async setState
.在这里阅读我的其他答案(但在您的问题是异步setState
的情况下),了解如何处理异步setState
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.