如何解构来自 useFetch 的对象?

Posted

技术标签:

【中文标题】如何解构来自 useFetch 的对象?【英文标题】:how to deconstruct an object that is coming from useFetch? 【发布时间】: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 ?? 【参考方案1】:

我会制作另一个组件,也许叫它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>
  );

【讨论】:

以上是关于如何解构来自 useFetch 的对象?的主要内容,如果未能解决你的问题,请参考以下文章

如何在Javascript中解构一个json对象数组

如何使用对象解构在 TypeScript 中导入 JSON?

打字稿如何进行对象解构赋值

如何使用包含连字符的键将对象解构为变量? [复制]

跨表连接时如何最好地索引/解构 json 对象?

嵌套对象类型解构