如果我获取动态数据,如何在不违反钩子规则的情况下将其放入 atomFamily 中?useSetRecoilState
需要我传入atomFamily(someIndex)
,但是对于动态数据,我在获取数据someIndex
之前没有。所以看起来我应该有,但这违反了钩子规则。const setterFactory = someKey => useSetRecoilState(useAtomFamily(someKey))
例子:
假设我有一个附带类型的 API 响应(和反冲 atomFamily)
type Foo = unknown & { index: string }
type Response = {
foos: Foo[]
}
const myAtomFamily = useAtomFamily<Foo, string>({
key: 'foo',
default: null,
})
declare const fetchFromApi = () => Promise<Foo[]>
所以如果我有一个自定义钩子,
const myHook = () => {
const fooSetter = useSetRecoilState(myAtomFamily(???))
useEffect(() => {
fetchFromApi().then(foos => {
foos.forEach(foo => fooSetter(???)(???))
})
}, [])
}