ReactJS 如何仅在条件为真时获取?

ReactJS How to fetch only if a condition is true?

我正在尝试找到一种正确的方法来使用 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 }) => {

}

我想做的是仅当 fetchContacts 等于 true 时创建一个由 const contactState= useFetchApi(() => findContacts(userId)) 定义的 contactState,然后传递此 contactStateUserInformation.

所以基本上,类似于:

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 }) => {

}

我对反应(以及开发)还很陌生,所以我不知道如何正确地实现它。 有什么建议吗?

谢谢。

您应该使用 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])