VScode跑通Remix.js官方的contact程序开发过程

目录

1 引言

2 安装并跑起来

3 设置根路由

4 用links来添加风格资源

​5 联系人路由的UI

6 添加联系人的UI组件

7 嵌套路由和出口

8 类型推理

9 Loader里的URL参数

10 验证参数并抛出响应


书接上回,我们已经跑通了remix的quick start项目,接下来看看第2个教程,官网宣称耗时30分钟来学习。

1 引言

We'll be building a small, but feature-rich app that lets you keep track of your contacts. There's no database or other "production ready" things, so we can stay focused on Remix. We expect it to take about 30m if you're following along, otherwise it's a quick read.

我们将建立一个小而功能丰富的联系人管理程序。没有数据库或其他东西,所以我们可以专注于Remix。如果你跟上写的话,我们预计大概要花30分,否则就很快就能读完了。

下图就是最后的效果。

2 安装并跑起来

首先,新建一个目录并转至目录下

在这个目录下,测试下面命令,目的是生成一个基本模板。

npx create-remix@latest --template remix-run/remix/templates/remix-tutorial

也可能不需要创建新目录,不过我们还是稳妥起见,在目录下执行这个命令,选择y后,一顿安装。

这就是全部过程了,会让你选择路径,我们输入了/d/web/...这里和我们创建的路径不一致。

最后git初始化失败了,没关系。文件夹快200m了。

接下来执行:

npm installnpm run dev

虽然过程有些错误,但是不影响。

启动app 成功。

3 设置根路由

根路由是要渲染的UI的基本组件。我们这里是用typescript来写的。

4 用links来添加风格资源

这里其实就是设置css。

While there are multiple ways to style your Remix app, we're going to use a plain stylesheet that's already been written to keep things focused on Remix.

虽然有多种方式来设置Remix应用程序风格,我们将使用一个简单的样式表。

You can import CSS files directly into JavaScript modules. The compiler will fingerprint the asset, save it to your assetsBuildDirectory, and provide your module with the publicly accessible href.

​你可以将CSS文件直接导入到JavaScript模块中。编译器将对资产进行识别,将其保存到你的assetsBuildDirectory中,并为你的模块提供可公开访问的href。

import type { LinksFunction } from "@remix-run/node";
// existing importsimport appStylesHref from "./app.css";export const links: LinksFunction = () => [{ rel: "stylesheet", href: appStylesHref },
];

​我们直接把这个段代码复制到root中,然后再执行依次npm run dev

看起来css已经加载了。成功。

Every route can export a links function. They will be collected and rendered into the <Links /> component we rendered in app/root.tsx.

​每条路由都可以导出一个links功能。它们将被收集并呈现到我们在app/root.tsx中呈现的<Links />组件中。

​The app should look something like this now. It sure is nice having a designer who can also write the CSS, isn't it? (Thank you, Jim ).

应用程序现在看起来应该是这样的。有一个能写CSS的设计师真是太好了,不是吗?(谢谢你,吉姆)。

​5 联系人路由的UI

If you click on one of the sidebar items you'll get the default 404 page. Let's create a route that matches the url /contacts/1.

如果您单击其中一个侧边栏项,您将获得默认的404页面。让我们创建一个匹配url /contacts/1的路由。

我试过了,确实是404.

创建app/routes目录以及相应的文件

mkdir app/routes
touch app/routes/contacts.\$contactId.tsx

In the Remix route file convention, . will create a / in the URL and $ makes a segment dynamic. We just created a route that will match URLs that look like this:

​在Remix路由文件约定中,.将在URL中创建一个/,而$将创建一个动态段。我们刚刚创建了一个路由,它将匹配如下所示的url:​

  • /contacts/123
  • /contacts/abc

6 添加联系人的UI组件

It's just a bunch of elements, feel free to copy/paste.

它只是一堆元素,随意复制/粘贴。

import { Form } from "@remix-run/react";
import type { FunctionComponent } from "react";import type { ContactRecord } from "../data";export default function Contact() {const contact = {first: "Your",last: "Name",avatar: "https://placekitten.com/g/200/200",twitter: "your_handle",notes: "Some notes",favorite: true,};return (<div id="contact"><div><imgalt={`${contact.first} ${contact.last} avatar`}key={contact.avatar}src={contact.avatar}/></div><div><h1>{contact.first || contact.last ? (<>{contact.first} {contact.last}</>) : (<i>No Name</i>)}{" "}<Favorite contact={contact} /></h1>{contact.twitter ? (<p><ahref={`https://twitter.com/${contact.twitter}`}>{contact.twitter}</a></p>) : null}{contact.notes ? <p>{contact.notes}</p> : null}<div><Form action="edit"><button type="submit">Edit</button></Form><Formaction="destroy"method="post"onSubmit={(event) => {const response = confirm("Please confirm you want to delete this record.");if (!response) {event.preventDefault();}}}><button type="submit">Delete</button></Form></div></div></div>);
}const Favorite: FunctionComponent<{contact: Pick<ContactRecord, "favorite">;
}> = ({ contact }) => {const favorite = contact.favorite;return (<Form method="post"><buttonaria-label={favorite? "Remove from favorites": "Add to favorites"}name="favorite"value={favorite ? "false" : "true"}>{favorite ? "★" : "☆"}</button></Form>);
};

Now if we click one of the links or visit /contacts/1 we get ... nothing new?

现在,如果我们点击其中一个链接或访问/联系人/1,我们得到…没有什么新的吗?

我试了下,其实就是不报404了。里面还用到了twitter的网页,确定我们能打开吗??

7 嵌套路由和出口

Since Remix is built on top of React Router, it supports nested routing. In order for child routes to render inside of parent layouts, we need to render an Outlet in the parent. Let's fix it, open up app/root.tsx and render an outlet inside.

​由于Remix是建立在React Router之上的,所以它支持嵌套路由。为了让子路由在父布局中呈现,我们需要在父布局中呈现一个Outlet。让我们修复它,打开app/root。并在里面渲染一个出口。

​这里涉及到一些代码的修改。import里新增一个outlet,然后在body里还要新增一个div。

import {Form,Links,LiveReload,Meta,Outlet,Scripts,ScrollRestoration,
} from "@remix-run/react";import type { LinksFunction } from "@remix-run/node";
// existing importsimport appStylesHref from "./app.css";export const links: LinksFunction = () => [{ rel: "stylesheet", href: appStylesHref },
];export default function App() {return (<html lang="en"><head><meta charSet="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><Meta /><Links /></head><body><div id="sidebar"><h1>Remix Contacts</h1><div><Form id="search-form" role="search"><inputid="q"aria-label="Search contacts"placeholder="Search"type="search"name="q"/><div id="search-spinner" aria-hidden hidden={true} /></Form><Form method="post"><button type="submit">New</button></Form></div><nav><ul><li><a href={`/contacts/1`}>Your Name</a></li><li><a href={`/contacts/2`}>Your Friend</a></li></ul></nav></div><div id="detail"><Outlet /></div><ScrollRestoration /><Scripts /><LiveReload /></body></html>);
}

刷新一下,重新run,确实出来联系人界面了,只是猫猫和示例的姿势不一样。

8 客户边路由

You may or may not have noticed, but when we click the links in the sidebar, the browser is doing a full document request for the next URL instead of client side routing.

您可能注意到,也可能没有注意到,当我们单击侧边栏中的链接时,浏览器正在对下一个URL进行完整的文档请求,而不是客户端路由。

Client side routing allows our app to update the URL without requesting another document from the server. Instead, the app can immediately render new UI. Let's make it happen with <Link>.

​客户端路由允许我们的应用程序更新URL,而不需要从服务器请求另一个文档。相反,应用程序可以立即呈现新的UI。让我们用<Link>实现它。

这段有点看不懂,先跟着做吧。

Change the sidebar <a href> to <Link to>

​将侧边栏的...改为...

这里又是改代码,import里新增Link,然后在div里做相应修改即可。

做完以后网页没啥变化。

You can open the network tab in the browser devtools to see that it's not requesting documents anymore.

您可以在浏览器devtools中打开network选项卡,查看它不再请求文档了。

这里没试,暂时没啥影响,不管了。

8 加载数据

URL segments, layouts, and data are more often than not coupled (tripled?) together. We can see it in this app already:

URL段、布局和数据通常是耦合在一起的(三倍?)我们可以在这个应用程序中看到它:

Because of this natural coupling, Remix has data conventions to get data into your route components easily.

由于这种自然耦合,Remix具有数据约定,可以轻松地将数据放入路由组件中。

There are two APIs we'll be using to load data, loader and useLoaderData. First we'll create and export a loader function in the root route and then render the data.

​我们将使用两个api来加载数据,loader和useLoaderData。首先,我们将在根路由中创建并导出一个加载器函数,然后渲染数据。

从root.tsx中导出一个loader函数,然后渲染数据。

import { json } from "@remix-run/node";import {Form,Link,Links,LiveReload,Meta,Outlet,Scripts,ScrollRestoration,useLoaderData,
} from "@remix-run/react";import { getContacts } from "./data";import type { LinksFunction } from "@remix-run/node";
// existing importsimport appStylesHref from "./app.css";export const links: LinksFunction = () => [{ rel: "stylesheet", href: appStylesHref },
];export const loader = async () => {const contacts = await getContacts();return json({ contacts });
};export default function App() {const { contacts } = useLoaderData();return (<html lang="en"><head><meta charSet="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><Meta /><Links /></head><body><div id="sidebar"><h1>Remix Contacts</h1><div><Form id="search-form" role="search"><inputid="q"aria-label="Search contacts"placeholder="Search"type="search"name="q"/><div id="search-spinner" aria-hidden hidden={true} /></Form><Form method="post"><button type="submit">New</button></Form></div><nav>{contacts.length ? (<ul>{contacts.map((contact) => (<li key={contact.id}><Link to={`contacts/${contact.id}`}>{contact.first || contact.last ? (<>{contact.first} {contact.last}</>) : (<i>No Name</i>)}{" "}{contact.favorite ? (<span>★</span>) : null}</Link></li>))}</ul>) : (<p><i>No contacts</i></p>)}</nav></div><div id="detail"><Outlet /></div><ScrollRestoration /><Scripts /><LiveReload /></body></html>);
}

​这个文件写完后,有2个报错

其中contacts上红线显示:

property contacts doesnot exist on type unknown ts2339

查了一下,挺复杂,主要是也不懂ts语法。

先不管,运行一下,结果居然能显示。也是服了。

可以看到,侧边栏有很多名字了,这就是数据。这些数据都是存在data.ts里的。

虽然报错,但总算是能运行,神奇啊。

8 类型推理

You may have noticed TypeScript complaining about the contact type inside the map. We can add a quick annotation to get type inference about our data with typeof loader:

你可能已经注意到TypeScript在抱怨map中的contact类型。我们可以通过typeof加载器添加一个快速注释来获取数据的类型推断:

onst { contacts } = useLoaderData<typeof loader>();

上面还说有错呢,结果这里就更正了。所以说一直往下看可能有惊喜,没必要浪费那20分钟。试一下也许就行呢。

虽然也不知道到底是啥错误,主要是不懂ts

9 Loader里的URL参数

Click on one of the sidebar links

We should be seeing our old static contact page again, with one difference: the URL now has a real ID for the record.

单击其中一个侧边栏链接

我们应该再次看到旧的静态联系人页面,但有一点不同:URL现在有了记录的真实ID。

Remember the $contactId part of the file name at app/routes/contacts.$contactId.tsx? These dynamic segments will match dynamic (changing) values in that position of the URL. We call these values in the URL "URL Params", or just "params" for short.

还记得app/routes/contacts文件名称中的$contactId部分吗?这些动态段将匹配URL中该位置的动态(变化)值。我们将URL中的这些值称为“URL参数”,或者简称为“参数”。

These params are passed to the loader with keys that match the dynamic segment. For example, our segment is named $contactId so the value will be passed as params.contactId.

这些参数与匹配动态段的键一起传递给加载器。例如,我们的段命名为$contactId,因此值将作为params.contactId传递。

These params are most often used to find a record by ID. Let's try it out.

这些参数最常用于按ID查找记录。我们来试一下。

Add a loader function to the contact page and access data with useLoaderData

往联系人页面添加一个loader函数,用useLoaderData来与数据交互。

只修改标住的地方就可以。我们修改完以后会发现报错,真是坑啊然而作者知道这个情况···这时候还不能运行···只能接着往下走。

10 验证参数并抛出响应

TypeScript is very upset with us, let's make it happy and see what that forces us to consider

TypeScript对我们非常不满,让我们让它高兴一下,看看这会迫使我们考虑什么

还是照着改。

First problem this highlights is we might have gotten the param's name wrong between the file name and the code (maybe you changed the name of the file!). Invariant is a handy function for throwing an error with a custom message when you anticipated a potential issue with your code.

这突出的第一个问题是,我们可能在文件名和代码之间获得了错误的参数名称(可能您更改了文件名!)。当您预计代码可能出现问题时,Invariant是一个方便的函数,用于抛出带有自定义消息的错误。

Next, the useLoaderData<typeof loader>() now knows that we got a contact or null (maybe there is no contact with that ID). This potential null is cumbersome for our component code and the TS errors are flying around still.

接下来,useLoaderData<typeof loader>()现在知道我们得到了一个联系人或null(可能没有联系人的ID)。对于我们的组件代码来说,这个潜在的null很麻烦,TS错误仍然在到处乱飞。

We could account for the possibility of the contact being not found in component code, but the webby thing to do is send a proper 404. We can do that in the loader and solve all of our problems at once.

我们可以考虑在组件代码中找不到联系人的可能性,但是web要做的事情是发送适当的404。我们可以在加载器中这样做,并一次解决所有问题。

上面一大堆,我页看不懂,只能是照着往下走

修改到这里,错误就全部没有了,神奇啊。

Now, if the user isn't found, code execution down this path stops and Remix renders the error path instead. Components in Remix can focus only on the happy path 😁

现在,如果没有找到用户,代码将停止沿此路径执行,Remix将呈现错误路径。Remix中的组件只能关注快乐路径。

运行一下

我只知道,这一步把头像加载出来了。里面全是胡子哥和大姐。要不就是秃头。没个能看的。

接下来的内容还挺多,今天暂时就到这里吧。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/225256.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux开发工具——gcc篇

gcc的使用 文章目录 gcc的使用 历史遗留问题&#xff08;普通用户sudo&#xff09; gcc编译过程 预处理&#xff08;进行宏替换&#xff09; 编译&#xff08;生成汇编&#xff09; 汇编&#xff08;生成机器可识别代码&#xff09; 链接&#xff08;生成可执行文件或库文件&a…

LSTM的记忆能力实验

长短期记忆网络&#xff08;Long Short-Term Memory Network&#xff0c;LSTM&#xff09;是一种可以有效缓解长程依赖问题的循环神经网络&#xff0e;LSTM 的特点是引入了一个新的内部状态&#xff08;Internal State) 和门控机制&#xff08;Gating Mechanism&#xff09;&am…

Kafka设计原理详解

Kafka核心总控制器 (Controller) 在Kafka集群中&#xff0c;通常会有一个或多个broker&#xff0c;其中一个会被选举为控制器 (Kafka Controller)&#xff0c;其主要职责是管理整个集群中所有分区和副本的状态。具体来说&#xff1a; 当某个分区的leader副本出现故障时&#…

基于gradio快速部署自己的深度学习模型(目标检测、图像分类、语义分割模型)

gradio是一款基于python的算法快速部署工具&#xff0c;本博文主要介绍使用gradio部署目标检测、图像分类、语义分割模型的部署。相比于flask&#xff0c;使用gradio不需要自己构造前端代码&#xff0c;只需要将后端接口写好即可。此外&#xff0c;基于gradio实现的项目&#x…

数据仓库【2】:架构

数据仓库【2】&#xff1a;架构 1、架构图2、ETL流程2.1、ETL -- Extract-Transform-Load2.1.1、数据抽取&#xff08;Extraction&#xff09;2.1.2、数据转换&#xff08;Transformation&#xff09;2.1.3、数据加载&#xff08; Loading &#xff09; 2.2、ETL工具2.2.1、结构…

浅谈数据仓库运营

一、背景 企业每天都会产生大量的数据&#xff0c;随着时间增长&#xff0c;数据会呈现几何增长&#xff0c;尤其在系统基建基础好的公司。好的数据仓库需要提前规划和好的运营&#xff0c;才能支持企业的发展&#xff0c;为企业提供数据分析基础。 二、目标 提高数据仓库存储…

【RocketMQ笔记02】安装RocketMQ可视化工具rocketmq-dashboard

这篇文章&#xff0c;主要介绍如何安装RocketMQ可视化工具rocketmq-dashboard。 目录 一、RocketMQ可视化界面 1.1、下载rocketmq-dashboard 1.2、修改配置文件 1.3、打包工程 1.4、启动rocketmq-dashboard 一、RocketMQ可视化界面 1.1、下载rocketmq-dashboard rocketm…

Jenkins 自动设置镜像版本号

使用Jenkins环境变量当作镜像版本号 这样version变量就是版本号,在镜像构建的过程中可以使用 docker build 之后&#xff0c;如果有自己的镜像库&#xff0c;肯定要docker push 一下 至于部署的步骤&#xff0c;一般需要stop并删除原有的容器.我这里用的是docker-compose。同样…

利用Jmeter做接口测试(功能测试)全流程分析!

利用Jmeter做接口测试怎么做呢&#xff1f;过程真的是超级简单。 明白了原理以后&#xff0c;把零碎的知识点填充进去就可以了。所以在学习的过程中&#xff0c;不管学什么&#xff0c;我一直都强调的是要循序渐进&#xff0c;和明白原理和逻辑。这篇文章就来介绍一下如何利用…

SpringCloud 整合 Canal+RabbitMQ+Redis 实现数据监听

1Canal介绍 Canal 指的是阿里巴巴开源的数据同步工具&#xff0c;用于数据库的实时增量数据订阅和消费。它可以针对 MySQL、MariaDB、Percona、阿里云RDS、Gtid模式下的异构数据同步等情况进行实时增量数据同步。 当前的 canal 支持源端 MySQL 版本包括 5.1.x , 5.5.x , 5.6.…

学习笔记15——前端和http协议

学习笔记系列开头惯例发布一些寻亲消息&#xff0c;感谢关注&#xff01; 链接&#xff1a;https://baobeihuijia.com/bbhj/ 关系 客户端&#xff1a;对连接访问到的前端代码进行解析和渲染&#xff0c;就是浏览器的内核服务器端&#xff1a;按照规则编写前端界面代码 解析标准…

GrayLog日志平台的基本使用-ssh接入Dashboards展示

这里使用的版本为graylog4.2.10 1、一键安装graylog4.2.10&#xff0c;解压zip包&#xff0c;执行脚本就行 链接&#xff1a;https://pan.baidu.com/s/11U7GpBZ1B7PXR8pyWVcHNw?pwdudln 提取码&#xff1a;udln 2、通过rsyslog采集系统日志&#xff0c;具体操作参考前面文…

【二叉树】【单调双向队列】LeetCode239:滑动窗口最大值

作者推荐 map|动态规划|单调栈|LeetCode975:奇偶跳 涉及知识点 单调双向队列 二叉树 题目 给你一个整数数组 nums&#xff0c;有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 返回 滑动…

Web组态可视化编辑器-by组态

演示地址&#xff1a; http://www.by-lot.com http://www.byzt.net web组态可视化编辑器&#xff1a;引领未来可视化编辑的新潮流 随着网络的普及和快速发展&#xff0c;web组态可视化编辑器应运而生&#xff0c;为人们在网络世界中创建和编辑内容提供了更加便捷的操作方式。这…

Zookeeper在分布式命名服务中的实践

Java学习面试指南&#xff1a;https://javaxiaobear.cn 命名服务是为系统中的资源提供标识能力。ZooKeeper的命名服务主要是利用ZooKeeper节点的树形分层结构和子节点的顺序维护能力&#xff0c;来为分布式系统中的资源命名。 哪些应用场景需要用到分布式命名服务呢&#xff1…

如何使用宝塔面板+Discuz+cpolar内网穿透工具搭建可远程访问论坛服务

文章目录 前言1.安装基础环境2.一键部署Discuz3.安装cpolar工具4.配置域名访问Discuz5.固定域名公网地址6.配置Discuz论坛 前言 Crossday Discuz! Board&#xff08;以下简称 Discuz!&#xff09;是一套通用的社区论坛软件系统&#xff0c;用户可以在不需要任何编程的基础上&a…

华为---USG6000V防火墙web基本配置示例

目录 1. 实验要求 2. 配置思路 3. 网络拓扑图 4. USG6000V防火墙端口和各终端相关配置 5. 在USG6000V防火墙web管理界面创建区域和添加相应端口 6. 给USG6000V防火墙端口配置IP地址 7. 配置通行策略 8. 测试验证 8.1 逐个删除策略&#xff0c;再看各区域终端通信情况 …

【QT】非常简单的登录界面实现

本系列是作者自学实践过程的记录 本文是关于登录界面设计 有问题欢迎讨论 效果图&#xff1a; 一、创建项目和主界面 创建Qt Widget Application 这里我们使用qmake而不是cmake 这是主界面&#xff0c;登录界面等后面再创建&#xff0c;这里要勾选上generate form&#xff0…

个性化定制的知识付费小程序,为用户提供个性化的知识服务,知识付费saas租户平台

明理信息科技知识付费saas租户平台 在当今数字化时代&#xff0c;知识付费已经成为一种趋势&#xff0c;越来越多的人愿意为有价值的知识付费。然而&#xff0c;公共知识付费平台虽然内容丰富&#xff0c;但难以满足个人或企业个性化的需求和品牌打造。同时&#xff0c;开发和…

【软件工程】可执行文件和数据分离

一、概述 可执行文件和数据分离是一种软件设计策略&#xff0c;旨在将程序代码和程序使用的数据分离存储。这种方法通常用于提高软件的模块化程度和灵活性&#xff0c;以及方便软件的管理和维护。 在可执行文件和数据分离中&#xff0c;程序代码通常以可执行文件的形式存储&a…