【问题标题】:how to deconstruct an object that is coming from useFetch?如何解构来自 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 ?? {}

标签: javascript reactjs ecmascript-6 frontend


【解决方案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>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-29
    • 2018-11-29
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 2016-11-28
    • 1970-01-01
    相关资源
    最近更新 更多