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钩子,它返回一些数据和其他东西。
在“食谱”变量中,我有一个由‘title,cookingTime,method’等组成的对象。
我的问题是,如何将这个配方对象解构为:
const {title, cookingTime, method, ingredients} = recipe如果我把它放在useFetch钩子下面,这段代码就不能工作了,因为在进入useEffect钩子之前,它将是空的,这个钩子位于useFetch中,知道吗?
发布于 2021-12-18 17:54:37
我会制作另一个组件,也许叫它RecipeData,您可以将从提取结果中的配方作为一个支柱传递下去,并且只有在数据存在的情况下才呈现。
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>
);
}https://stackoverflow.com/questions/70405713
复制相似问题