如何解构来自 useFetch 的对象?

how to deconstruct an object that is coming from useFetch?

a react document about my question

import { useParams } from 'react-router-dom';
import { useFetch } from '../../hooks/useFetch';
import { URL } from '../../util/fetchURL';

export default function Recipe() {
  const { id } = useParams();

  const { data: recipe, isPending, error } = useFetch(`${URL}/${id}`);

  return (
    <div className='recipe'>
      {error && <p className='error'>{error}</p>}
      {isPending && <p className='loading'>loding...</p>}

      {recipe && (
        <>
          <h2 className='page-title'>{title}</h2>
          <p>Takes {cookingTime} to cook.</p>
          <ul>
            {ingredients.map((ing) => (
              <li key={ing}>{ing}</li>
            ))}
          </ul>
          <p className='method'>{method}</p>
        </>
      )}
    </div>
  );
}

基本上,我有一个自定义的 useFetch 挂钩,可以返回一些数据和其他一些东西。

在'recipe'变量中,我有一个由''title, cookingTime, method'等组成的对象

我的问题是,如何将这个食谱对象解构为:

  const {title, cookingTime, method, ingredients} = recipe

如果我把它放在 useFetch 钩子下面,这段代码将不起作用,因为一开始,在进入 useFetch 内部的 useEffect 钩子之前它会是空的,知道吗?

我会制作另一个组件,也许称之为 RecipeData,您将获取结果中的配方作为 prop 传递下来,并且仅在数据存在时才渲染。

const RecipeData = ({ recipe }) => {
  const {title, cookingTime, method, ingredients} = recipe;
  return (<>
    <h2 className='page-title'>{title}</h2>
    <p>Takes {cookingTime} to cook.</p>
    ...
  );
};
export default function Recipe() {
  const { id } = useParams();

  const { data: recipe, isPending, error } = useFetch(`${URL}/${id}`);
  return (
    <div className='recipe'>
      {error && <p className='error'>{error}</p>}
      {isPending && <p className='loading'>loding...</p>}

      {recipe && <RecipeData recipe={recipe} />}
    </div>
  );
}