【发布时间】:2020-02-18 08:15:04
【问题描述】:
我想要一个控制选择的钩子,但它的初始状态可以通过 url 和 api 调用来定义。
这是我想要实现的行为:
- 组件通过异步调用api获取文档列表(result.value将在一段时间后设置)
- 可以在 url 中设置文档的 id,如果 match 不是 "false",match.params.id 会提取它
- useState 控制一个选择,如果(在 api 调用之后)在 url 中定义了一个 id,并且在文档列表中找到了这个 id,我希望将索引设置为这个值
这是我尝试过的(当然它不起作用):
const match = useRouteMatch('/document/:id') //react-router
const result = useAsync(api.getDocuments, []) //react-use
const [selectIndex, setSelectIndex] = useState(match && !(result.loading || result.error) && result.value.documents.findIndex(({_id}) => _id === match.params.id))
基本上我想为 useState 设置一个异步初始状态
我觉得 useEffect 可能有用,但我仍然不知道如何使用它
【问题讨论】:
-
无法将初始状态设置为异步操作的值。你能不更新状态吗?
-
@Chris 我没有在结果更新时触发回调
-
“结果”是承诺吗?
-
@DavinTryon 结果不是承诺,它是更新时重新呈现的对象github.com/streamich/react-use/blob/master/docs/useAsync.md
标签: reactjs react-hooks