0

我正在尝试找到一种useFecthApi有条件地使用的正确方法。

我有以下组件:

export const DetailedUser: FC = () => {
  const userState = useFetchApi(() => findUser(userId))

  const fetchContacts = mustFecthContacts() // implemenattion does not matter
  return (
    <>
       <UserInformation userState={userState } />
    </>
  )
}
type Props = Readonly<{
  userState: State<UserDetails>
}>

export const UserInformation : FC<Props> = ({ userState }) => {

}

我想做的是创建一个仅当等于的contactState定义,然后将其传递给.const contactState= useFetchApi(() => findContacts(userId))fetchContactstruecontactStateUserInformation

所以基本上,类似:

export const DetailedUser: FC = () => {
  const userState = useFetchApi(() => findUser(userId))
  // fetchContacts is a boolean (implementation is not important)
  const fetchContacts = mustFecthContacts()

  const contactStates = fetchContacts ? useFetchApi(() => findContacts(userId)) : undefined
  return (
    <>
       <UserInformation userState={userState} contactsState = {contactStates } />
    </>
  )
}
type Props = Readonly<{
  userState: State<UserDetails>,
  contactStates? : State<ContactDetails>
}>

export const UserInformation : FC<Props> = ({ userState, contactStates }) => {

}

我对做出反应(以及对叶状体的发展)还很陌生,所以我不知道如何正确地实现这一点。有什么建议吗?

谢谢。

4

1 回答 1

1

您应该使用useEffect钩子来获取数据。并且还将useState数据本地存储在组件中。

就像是:

// this stores the userState properly
const [userState, setUserState] = useState(() => {
  return useFetchApi(() => findContacts(userId))
});

// this triggers everytime fetchContacts changes and will
// fetch new data if fetchContacts is "truthy"
useEffect(() => {
  if(!!fetchContacts) {
    const userData = useFetchApi(() => findContacts(userId))
    setUserState(userData)
  }
}, [fetchContacts])
于 2020-12-12T15:39:06.957 回答