【发布时间】:2022-01-21 02:52:24
【问题描述】:
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 挂钩,可以返回一些数据和其他一些东西。
在“食谱”变量中,我有一个由“标题、烹饪时间、方法”等组成的对象。
我的问题是,如何将这个配方对象解构为:
const {title, cookingTime, method, ingredients} = recipe
如果我把它放在 useFetch 钩子下面,这段代码将不起作用,因为一开始,在进入 useFetch 内部的 useEffect 钩子之前它将为空,知道吗?
【问题讨论】:
-
您可以使用默认值:
const {...} = recipe ?? {}。
标签: javascript reactjs ecmascript-6 frontend