首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解构来自useFetch的对象?

如何解构来自useFetch的对象?
EN

Stack Overflow用户
提问于 2021-12-18 17:50:29
回答 1查看 49关注 0票数 0

对我的问题作出反应的文件

代码语言:javascript
复制
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’等组成的对象。

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

代码语言:javascript
复制
  const {title, cookingTime, method, ingredients} = recipe

如果我把它放在useFetch钩子下面,这段代码就不能工作了,因为在进入useEffect钩子之前,它将是空的,这个钩子位于useFetch中,知道吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-18 17:54:37

我会制作另一个组件,也许叫它RecipeData,您可以将从提取结果中的配方作为一个支柱传递下去,并且只有在数据存在的情况下才呈现。

代码语言:javascript
复制
const RecipeData = ({ recipe }) => {
  const {title, cookingTime, method, ingredients} = recipe;
  return (<>
    <h2 className='page-title'>{title}</h2>
    <p>Takes {cookingTime} to cook.</p>
    ...
  );
};
代码语言:javascript
复制
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>
  );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70405713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档