【发布时间】:2020-03-25 17:28:18
【问题描述】:
我使用带有 Apollo 客户端的 React 组件作为功能组件。我的主要搜索组件的函数体如下所示:
function SearchContainer(props) {
const [begTime, setBegTime] = useState('')
const runSearch(begin_time) {
console.log('begin_time: ', begin_time) <== The printed value is Ok!
setBegTime(begin_time) <=== Use hook to set the value of begTime
console.log('begTime: ', begTime) <=== The output shows no change in begTime. Why?
}
return (
// Use SearchForm to get the search parameters.
<SearchForm
handleSearch={runSearch} <== Use SearchForm to get begin_time back into this component.
/>
// Provide the parameters from SearchForm and run the useQuery from Apollo using this parameters.
<SearchResults
begTime={begTime}
/>
)
}
SearchForm 只是一个普通的表单,它是一个带有 useState 钩子的 React 函数组件,并在表单上调用提交 hanldeSearch 函数。
function SearchForm({handleSearch}) { <== handleSearch function from the parent component.
const handleSubmit = (begin_time) => {
handleSearch(begin_time) <== This call works and the value will be provided to the parent.
}
...
}
我对这段代码的想法是创建 2 个独立的组件。一个组件(SearchForm)应该获取参数。其他组件 (SearchResults) 将获取此参数作为参数,使用 useQuery 运行查询并显示结果。
但 useState 钩子在我的情况下不能很好地工作。有趣的是,如果我两次调用相应的搜索表单,我可以在 runSearch 函数中看到 begTime 获得了先前的搜索值而不是初始值。所以显然 useState 是可行的,但我想用当前值而不是以前的值来运行搜索。
是否有可能使用 React 钩子创建这样的组件?这是我第一次使用钩子而不是类的大测试。
提前致谢
安德烈
【问题讨论】:
标签: react-hooks