【发布时间】: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'},() =>{console.log(this.stste.my_var);});
标签: reactjs react-hooks react-context