0

如果我获取动态数据,如何在不违反钩子规则的情况下将其放入 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(???)(???))
    })
  }, [])
}
4

1 回答 1

0

您可以useRecoilCallback为此使用钩子,它基本上是一个工厂钩子,可让您访问该set功能:

const useMyHook = () => {
  const fetchAndSet = useRecoilCallback(({set}) => async () => {
    const foos = await fetchFromApi();

    foos.forEach(foo => set(myAtomFamily(foo.id), foo))
  }, [])

  useEffect(fetchAndSet, [])
}
于 2021-08-10T06:48:04.640 回答