[英]Curly braces inside array destructuring in return from a function
I can´t understand how the curly braces work (or what are they supposed to do) in the return of this custom hook.我无法理解大括号在返回这个自定义钩子时是如何工作的(或者他们应该做什么)。 I know it´s destructuring, I just don´t understand the need for them.
我知道这是解构,我只是不明白对它们的需要。 Could anyone explain?
谁能解释一下?
const useHackerNewsApi = () => {
const [data, setData] = useState({ hits: [] });
const [url, setUrl] = useState(
'https://hn.algolia.com/api/v1/search?query=redux',
);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const result = await axios(url);
setData(result.data);
} catch (error) {
setIsError(true);
}
setIsLoading(false);
};
fetchData();
}, [url]);
return [{ data, isLoading, isError }, setUrl];
}
You're basically returning an array that contains an Object at the 0th index and setUrl
method at the second index.您基本上是在返回一个数组,该数组在第 0 个索引处包含一个 Object,在第二个索引处包含
setUrl
方法。
The return value would be implicitly converted into:返回值将被隐式转换为:
[{
data: data,
isLoading: isLoading,
isError: isError
}, setUrl]
That's why you'd be able to use it like this in your Component:这就是为什么你可以在你的组件中像这样使用它:
import React, { useState } from "react";
import { useHackerNewsApi } from "./useHackerNewsAPI";
export default ({ name }) => {
const [{ data, isLoading, isError }, setUrl] = useHackerNewsApi();
return <h1>
<pre> Data - { JSON.stringify(data) }</pre>
<pre> isLoading - { isLoading }</pre>
<pre> isError - { isError }</pre>
</h1>;
};
Here's a Working Demo for your ref.
这是供您参考的工作演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.