【问题标题】:Why is it requiring two clicks to execute state change in react?为什么需要两次单击才能在反应中执行状态更改?
【发布时间】:2020-04-14 00:54:42
【问题描述】:

我很难等待状态变化。我正在使用反应钩子和上下文。

基本上,我有一个自定义下拉菜单,这里没有使用表单元素。点击时,它会运行一个函数来改变两个参数的状态:

// 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);
  };

所以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() 基本上运行一个在我的上下文中可用的函数,它为我的 axios 请求构建这些参数。每次单击时,都需要单击两次才能运行该想法。有时它会按预期运行,但大多数时候需要单击两次。

我遇到这个问题的任何原因?

任何帮助将不胜感激!

【问题讨论】:

  • 我没有使用钩子,但是在 React 状态下,在更新状态后我执行了函数,就像这样:this.setState({my_var: 'new_value'},() =&gt;{console.log(this.stste.my_var);});

标签: reactjs react-hooks react-context


【解决方案1】:

试试这个

const onClick = data => {
  const newFilter = { ...filter, ...data }
  setFilter(newFilter)
  filterIdeas(newFilter)
}

代替

const onClick = data => {
  setFilter({ ...filter, ...data })
  filterIdeas(filter)
}

在 React 中 setState 是异步的,我猜这是你的问题。尝试上面的代码,如果它有效并且您不完全理解,请在下面发表评论,我将编辑答案以更清楚地解释。阅读我的other answer here(如果你的问题是异步的setState,了解如何处理异步setState

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2019-05-30
    • 2018-05-30
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多