關于我的問題的反應檔案
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 鉤子,可以回傳一些資料和其他一些東西。
在“食譜”變數中,我有一個由“標題、烹飪時間、方法”等組成的物件。
我的問題是,如何將這個配方物件解構為:
const {title, cookingTime, method, ingredients} = recipe
如果我將它放在 useFetch 鉤子下方,此代碼將不起作用,因為起初,在進入 useFetch 內部的 useEffect 鉤子之前,它將為空,知道嗎?
uj5u.com熱心網友回復:
我會制作另一個組件,也許稱之為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://www.uj5u.com/gongcheng/386085.html
標籤:javascript 反应 ecmascript-6 前端
