概述
You need to have a basic understanding of React to follow along this article. 您需要对React有一个基本的了解才能跟随本文。 SWR is a lightweight, backend agnostic library developed by Vercel which allows us to fetch, re-fetch and cache the data with the help of React Hooks. SWR是由Vercel开发的轻量级后端不可知库,它使我们能够在React Hooks的帮助下获取,重新获取和缓存数据。 The name SWR is derived from “stale-while-revalidated.” When we ask SWR to make a request, it first provides us with cached data(stale) and then makes the request (revalidate), and finally provides an up to date data. 名称SWR源自“重新验证时失效”。 当我们要求SWR发出请求时,它首先为我们提供缓存的数据(陈旧),然后发出请求(重新验证),最后提供最新数据。 These are some of the features of SWR: 这些是SWR的一些功能: With these features, SWR makes our React App more user friendly and snappy. 借助这些功能,SWR使我们的React App更加用户友好和灵活。 So far, we have discussed SWR and it’s features, let’s now create the app. 到目前为止,我们已经讨论了SWR及其功能,现在让我们创建该应用程序。 Our app will look something like this: 我们的应用程序将如下所示: This is the index page for our app. It displays the list of article’s titles and their points. If a user clicks any of these titles, the user gets directed to the /news route with id as the query. Using the id from the query, we provide more information about the title in the /news route. Our /news will look like this: 这是我们的应用程序的索引页面。 它显示文章标题及其要点的列表。 如果用户单击这些标题中的任何一个,则该用户将被定向到ID为查询的/ news路由。 使用查询中的ID,我们在/ news路由中提供有关标题的更多信息。 我们的/ 新闻看起来像这样: We won’t be focusing much on styling our app in this article, okay? 我们不会在本文中集中精力设计应用程序的样式,好吗? Let’s now set up our app. For that, let’s write the following command in the terminal: 现在设置我们的应用程序。 为此,让我们在终端中编写以下命令: After the installation is complete, delete the folder called public in the main project directory. This should make the folder structure look like this: 安装完成后,删除主项目目录中名为public的文件夹。 这应该使文件夹结构如下所示: Notice that I have also removed the pages/api directory too. Let’s also remove the styles directory really quick from our main project directory. This should make our folder structure look like this: 注意,我也删除了pages / api目录。 让我们也从我们的主项目目录中快速删除样式目录。 这应该使我们的文件夹结构如下所示: Let’s now install some of the packages we need. For that, let’s fire up our terminal and write the following command: 现在让我们安装一些我们需要的软件包。 为此,让我们启动终端并编写以下命令: Here, we will be using bootstrap for styling our app. 在这里,我们将使用引导程序对应用程序进行样式设置。 You might be asking, why are we even using Axios at all if SWR is supposed to be the library for data fetching? That’s a good question. The purpose of SWR is to cache the data after making requests to the backend. We will always require fetch API, or Axios, or some other libraries to make the requests in SWR. The data received from those libraries or APIs will be handled and cached by SWR, making our React app more reactive. Remember, SWR is more complex than the request libraries or APIs. 您可能会问,如果SWR应该用作数据提取库,我们为什么还要使用Axios? 这是个好问题。 SWR的目的是在向后端发出请求后缓存数据。 我们将始终需要获取API,Axios或其他一些库才能在SWR中发出请求。 从这些库或API接收的数据将由SWR处理和缓存,从而使我们的React应用程序更具React性。 请记住,SWR比请求库或API更复杂。 Okay. Let’s now open up the _app.js file and make some changes. Our _app.js file should look like this: 好的。 现在让我们打开_app.js文件并进行一些更改。 我们的_app.js文件应如下所示: Here, we have imported the bootstrap’s CSS file and removed the import of the preexisting CSS file. Others are the same. 在这里,我们已经导入了引导程序CSS文件,并删除了先前存在CSS文件的导入。 其他都一样。 Let’s now work on our index page. Before doing that, Let’s create a new file called news.js inside of the pages directory. 现在让我们在索引页面上工作。 在此之前,让我们在pages目录中创建一个名为news.js的新文件。 All right! Let’s now work on index.js. First, you need to remove the pre-existing code in the file. Then, let’s write the following lines of code: 行! 现在让我们处理index.js 。 首先,您需要删除文件中预先存在的代码。 然后,让我们编写以下代码行: Most of the things here might look familiar to you, right? At line 1 and 2, we imported 您可能对这里的大多数东西都很熟悉,对吧? 在第1行和第2行,我们导入了 There are other ways of creating the 还有其他创建 Let’s take a look at the 让我们看一下第9行的 If there exists any error we provide the error message to the user ( at line 12). 如果存在任何错误,我们将错误消息提供给用户(第12行)。 As I had said previously, if 正如我之前所说,如果 If the data exist, we render the 如果数据存在,我们将渲染 Until now, we had worked on index.js file, let’s now work on news.js file. Let’s open the news.js file and write the following lines of code in the file: 到目前为止,我们已经处理index.js文件,现在让我们处理news.js文件。 让我们打开news.js文件,并在文件中编写以下代码行: Let’s take a closer look at this file. 让我们仔细看看这个文件。 At line 1, we imported 在第1行,我们从 At line 7, we have defined the 在第7行,我们定义了 At line 13, we have used 在第13行,我们使用了 If there occurs any error, we provide that information to the user (at line 15), as we had done in the index.js file. 如果发生任何错误,我们就像在index.js文件中所做的那样,将这些信息提供给用户(第15行)。 If the data is loading, we render the loading info to the user (from line to 16 to 26), as we had done previously in the index.js file. 如果数据正在加载,则像以前在index.js文件中所做的那样,将加载信息呈现给用户(从第16行到第26行)。 When the data exist, we render the component 当数据存在时,我们在第30行渲染组件 We have finally completed working on the news.js file. Let’s now work on the 我们终于完成了news.js文件的工作。 现在让我们来处理 After that, let’s open up the Description.js and write the following lines of code: 之后,让我们打开Description.js并编写以下代码行: Here, we have created 在这里,我们创建了 At line 6, we render the title of the news with the help of 在第6行,我们借助 Now that we have worked on Description.js , let’s now work on NewsList.js file. Let’s write the following lines of code in the file: 现在,我们已经处理了Description.js ,现在让我们来处理NewsList.js文件。 让我们在文件中编写以下代码行: At line 1, we imported 在第1行,我们从 With this, we have completed creating the app. You now can try this out. 至此,我们已经完成了应用的创建。 现在,您可以尝试一下。 While creating the app, we had configured the SWR locally. We can configure SWR globally too. For that, you might want to take a look at this part of the documentation. If you want to know about fetching the data with SWR using fetch or GraphQL, you can take a look at this part of the documentation. 在创建应用程序时,我们已经在本地配置了SWR。 我们也可以全局配置SWR。 为此,您可能需要看一下文档的这一部分 。 如果您想了解使用fetch或GraphQL通过SWR来获取数据的信息,可以查看文档的这一部分 。 Did you know that we have three publications and a YouTube channel? Find links to everything at plainenglish.io! 您知道我们有三个出版物和一个YouTube频道吗? 在plainenglish.io上找到所有内容的链接! 翻译自: https://medium.com/javascript-in-plain-english/getting-started-with-data-fetching-in-react-with-swr-bfb37ec0c65d SWR介绍 (Introduction to SWR)
SWR的特点 (Features of SWR)
npx create-next-app .
npm i bootstrap axios swr
import "bootstrap/dist/css/bootstrap.min.css";
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;}export default MyApp;import useSWR from "swr";
import axios from "axios";
import NewsList from "../component/NewsList";
const url = "https://node-hnapi.herokuapp.com/news";
const fetcher = (...args) => axios.get(...args).then((res) => res.data);
export default function Index() {
const { data, error } = useSWR(url, fetcher);
if (error) return <h2> Some error occured </h2>;
if (!error && !data)
return (
<div className="d-flex align-items-center container">
<strong>Loading...</strong>
<div
className="spinner-border ml-auto"
role="status"
aria-hidden="true"
></div>
</div>
);
return (
<div>
<NewsList newsList={data} />
</div>
);
}
useSWR
and axios
. Then, at line 4, we imported the NewsList
component — we will be creating it shortly. At line 6, we created a constant called url
, which is the URL through which we’ll be receiving the list of articles. Then, we have a fetcher
function at line 7. The purpose of the fetcher
function is to return the JSON data. We’ll be using the fetcher
function while working with useSWR
. You can see, in the fetcher
function, I have used the rest operator to spread the args
. Then, I again used the rest operator while using the .get
method of axios
.useSWR
和axios
。 然后,在第4行,我们导入了NewsList
组件-我们将在不久后创建它。 在第6行,我们创建了一个名为url
的常量,这是我们将通过其接收文章列表的URL。 然后,我们有一个fetcher
在第7行功能的用途fetcher
函数返回的JSON数据。 我们将使用fetcher
功能与工作时useSWR
。 您可以看到,在fetcher
函数中,我使用了rest运算符来扩展args
。 然后,在使用axios
的.get
方法时,我再次使用了rest运算符。 fetcher
function. We won’t be discussing it here, okay?fetcher
功能的方法。 我们不会在这里讨论它,好吗? Index
function, at line 9. We have exported this function. At line 10, we have used useSWR
. The useSWR
takes url
as the first argument and fetcher
as the second argument. The useSWR
returns us with data
and error
. Both the data
and error
can’t exist at the same time. If both don’t exist, this means the data is loading.Index
函数。我们已经导出了此函数。 在第10行,我们使用了useSWR
。 该useSWR
采用url
作为第一个参数,并fetcher
作为第二个参数。 useSWR
我们返回data
和error
。 data
和error
不能同时存在。 如果两者都不存在,则意味着正在加载数据。 error
and data
don’t exist, the data is currently loading. When the data is loading, we show the user that the data is being loaded (from line 13 to 23). There, I have used bootstrap to add a spinner. If you don’t know about creating a spinner with bootstrap, follow this link to their documentation on creating spinners.error
和data
不存在,则数据正在加载中。 当数据加载时,我们向用户显示数据正在加载(从第13行到第23行)。 在那里,我使用了引导程序来添加微调器。 如果您不知道如何使用引导程序创建微调器,请通过此链接访问其有关创建微调器的文档。 NewsList
component (from line 25 to 29). The NewsList
component requires newsList
as the props. We have provided data
as the value to newsList
prop, at line 27.NewsList
组件(从第25行到第29行)。 NewsList
组件需要newsList
作为道具。 我们已在第27 newsList
data
作为值提供给newsList
。 import { useRouter } from "next/router";
import axios from "axios";
import useSWR from "swr";
import Description from "../component/Description";
const url = "https://node-hnapi.herokuapp.com/item/";
const fetcher = (...args) => axios.get(...args).then((res) => res.data);
const News = () => {
const router = useRouter();
const { data, error } = useSWR(url + router.query.id, fetcher);
if (error) return <h2> Some error occured </h2>;
if (!error && !data)
return (
<div className="d-flex align-items-center container">
<strong>Loading...</strong>
<div
className="spinner-border ml-auto"
role="status"
aria-hidden="true"
></div>
</div>
);
return (
<>
<Description news={data} />
</>
);
};
export default News;
useRouter
from next/router
. At line 2, we imported axios
. At line 3, we imported useSWR
. At line 5, we imported Description
component.next/router
导入了useRouter
。 在第2行,我们导入了axios
。 在第3行,我们导入了useSWR
。 在第5行,我们导入了Description
组件。 url
constant. The url
, here, contains the URL to the news’ description or data. Then, at line 8, we have defined a fetcher
function. You now know what the fetcher
function does. So, I won’t describe it again. At line 10, we created the News
function. At line 11, we have stored the withRouter()
hook in the router
constant.url
常量。 此处的url
包含新闻描述或数据的URL。 然后,在第8行,我们定义了fetcher
函数。 现在您知道了fetcher
功能的作用。 因此,我不再赘述。 在第10行,我们创建了News
函数。 在第11行,我们将withRouter()
挂钩存储在router
常量中。 useSWR
. Notice that, we’ve used url + router.query.id
as the first argument and fetcher
as the second. In order to get the data about a particular news or article, the URL https://node-hnapi.herokuapp.com/item/:id should contain id as the parameter. We are providing that id through the router.query.id
. The useSWR
provides data
and error
— you already know that.useSWR
。 请注意,我们使用url + router.query.id
作为第一个参数,并fetcher
作为第二。 为了获取有关特定新闻或文章的数据,URL https://node-hnapi.herokuapp.com/item/:id应该包含id作为参数。 我们通过router.query.id
提供该ID。 useSWR
提供data
和error
-您已经知道了。 Description
at line 30. We have provided the Description
component with news
, as the props, which contains data
as the value.Description
。我们为Description
组件提供了props news
,其中包含data
作为值。 NewsList
and Description
component. Let’s create a directory called component in our main project directory. Then, create two files called Description.js and NewsList.js in the component directory. This should make our folder structure look like this:NewsList
和Description
组件。 让我们在主项目目录中创建一个名为component的目录。 然后,在组件目录中创建两个名为Description.js和NewsList.js的文件。 这应该使我们的文件夹结构如下所示: const Description = ({ news }) => {
return (
<>
<div className="container">
<div>
<h1> {news.title} </h1>
<div className="row mt-2">
<strong className="col-6 h5"> by -- {news.user} </strong>
<strong className="col-6 h5">Published : {news.time_ago}</strong>
</div>
<div className="row mb-2">
<em className="col-6 h5">
{" "}
<a href={news.url} target="blank">
View Article{" "}
</a>{" "}
</em>
<em className="col-6 h5">
{" "}
Points :{" "}
<span className="badge badge-primary">{news.points}</span>
</em>
</div>
<h3>Comments: {news.comments_count}</h3>
</div>
</div>
</>
);
};
export default Description;
Description
which is an arrow function. Notice that at line 1, we’ve used object destructuring to get the news
props.Description
,这是一个箭头函数。 请注意,在第1行,我们使用对象分解来获取news
道具。 news.title
. At line 9, we render the author of the post using news.user
. At line 10, we render how long ago the post was published using news.time_ago
. From line 16 to 18, we added an a
tag to provide the reference to the post. The href
contains the link to the article with the help of news.url
. At line 23, we render the points of the article using news.points
. Then, at line 27, we render the count of comments to the article using news.comments_count
. Finally, we exported the Description
at line 34.news.title
渲染新闻的标题。 在第9行,我们使用news.user
呈现帖子的作者。 在第10行,我们使用news.time_ago
渲染了多久以前发布的news.time_ago
。 从第16行到第18行,我们添加了a
标签,以提供对该帖子的引用。 href
包含在news.url
的帮助下news.url
文章的链接。 在第23行,我们使用news.points
渲染文章的news.points
。 然后,在第27行,我们使用news.comments_count
呈现对文章的评论计数。 最后,我们在第34行导出了Description
。 import Link from "next/link";
const NewsList = ({ newsList }) => {
return (
<>
<div className="list-group h-100">
{newsList.map((news) => (
<Link
href={{ pathname: "/news", query: { id: news.id } }}
key={news.id}
>
<a className="list-group-item list-group-item-action text-truncate">
{news.title}
<br />
<strong>Points:</strong>{" "}
<span className="badge badge-primary badge-pill">
{news.points}
</span>
</a>
</Link>
))}
</div>
</>
);
};
export default NewsList;
Link
from next/link
. At line 3, we created an arrow function called NewsList
. Notice that, we have destructured the newsList
from the props, at line 3. At line 7, we mapped through the newsList
. We display the title of the news at line 13 using news.title
. We display the points of the news using news.points
, at line 17. Whenever, user clicks on any of these news, we direct the user to the /news route with the id
as the query. To do that, we have used the Link
(line 8 to 11). We have provided the key
to the Link
, at line 10. The key
contains news.id
as its value. At line 9, we’ve used href
to direct the user to the /news route. The href
here contains pathname
and query
. We have provided "/news"
as the value to the pathname
. The query
, on the other hand, contains an object. That object has id
property with news.id
as the value. We finally exported NewsList
at line 27.next/link
导入了Link
。 在第3行,我们创建了一个名为NewsList
的箭头函数。 注意,在第3行,我们已经从props解构了newsList
。在第7行,我们通过newsList
进行了newsList
。 我们使用news.title
在第13行显示新闻的标题。 我们在第17行使用news.points
显示新闻的要点。只要用户单击这些新闻中的任何一个,我们news.points
用户引导到/ news路由,其id
为查询。 为此,我们使用了Link
(第8至11行)。 我们已经提供了key
的Link
,在线10 key
包含news.id
作为其值。 在第9行,我们使用href
将用户定向到/ news路由。 这里的href
包含pathname
和query
。 我们提供了"/news"
作为pathname
的值。 另一方面, query
包含一个对象。 该对象具有id
属性,其值为news.id
我们最终在第27行导出了NewsList
。 进一步阅读 (Further Reading)
普通英语JavaScript (JavaScript In Plain English)
最后
以上就是称心大神为你收集整理的与swrReact开始获取数据的全部内容,希望文章能够帮你解决与swrReact开始获取数据所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复