react hook_创建一个自定义useFetch()React Hook

react hook

介绍 (Introduction)

A custom hook is a JavaScript function with a unique naming convention that requires the function name to start with use and has the ability to call other hooks.

定制钩子是具有唯一命名约定JavaScript函数,该约定要求函数名从use开始就use ,并且能够调用其他钩子。

The idea behind custom hooks is to extract component logic in to reusable functions.

自定义钩子的思想是将组件逻辑提取到可重用的函数中。

Often times as we build out React applications, we see ourselves writing almost the same exact codes in two or more different components. Ideally what we could do in such cases would be to extract that recurrent logic into a reusable piece of code (hook) and reuse it where needed.

通常,在构建React应用程序时,我们会看到自己在两个或更多不同的组件中编写几乎完全相同的代码。 理想情况下,在这种情况下,我们可以做的是将循环逻辑提取到可重用的代码段(挂钩)中,并在需要时重用它。

Before hooks, we shared stateful logic between components using render props and higher order components, however, since the introduction of hooks and since we came to understand how neat they make these concepts, it no longer made sense to keep using those. Basically, when we want to share logic between two JavaScript functions, we extract it to a third function possibly because both components and hooks are equally just functions.

在使用钩子之前,我们使用渲染道具和更高阶的组件在组件之间共享状态逻辑,但是,由于引入了钩子,并且由于我们逐渐了解了钩子如何使这些概念变得整洁,因此不再使用它们就不再有意义。 基本上,当我们想在两个JavaScript函数之间共享逻辑时,我们可能会将其提取到第三个函数,这可能是因为组件和挂钩都只是函数而已。

将Fetch抽象为useFetch() (Abstracting Fetch into useFetch())

Compared to using the native fetch API out of the box, abstracting it into the useFetch hook gives it a one-liner ability, more declarative code style, reusable logic, and overall cleaner code. Take a look at this useFetch example:

与开箱即useFetch使用本机获取API相比,将其抽象到useFetch挂钩中可以使它具有useFetch功能,更具声明性的代码样式,可重用的逻辑以及整体更简洁的代码。 看一下这个useFetch示例:

const useFetch = (url, options) => {
  const [response, setResponse] = React.useState(null);
  useEffect(async () => {
      const res = await fetch(url, options);
      const json = await res.json();
      setResponse(json);
  });
  return response;
};

Here, the effect hook, called useEffect

你可能感兴趣的:(python,javascript,java,vue,js,ViewUI)