WHAT – React 学习系列(二)

作者 : admin 本文共7546个字,预计阅读时间需要19分钟 发布时间: 2024-06-17 共1人阅读

目录

  • 一、官方介绍
  • 二、框架具体对比
    • 1. Next.js(Pages Router)
    • 2. Remix
    • 3. Gatsby
    • 4. Expo(用于原生应用)
    • 5. Next.js(App Router)
      • Next.js App Router
        • 主要特性
        • 与 Pages Router 的对比
      • 具体使用示例
        • 创建 App Router 项目
        • 目录结构示例
        • 示例代码
      • 总结

这一篇主要介绍React在线编码和框架。

一、官方介绍

Outside of the React documentation, there are many online sandboxes that support React: for example, CodeSandbox, StackBlitz, or CodePen.

If you want to build a new app or a new website fully with React, we recommend picking one of the React-powered frameworks popular in the community. By starting with a framework, you can get started with React quickly, and avoid essentially building your own framework later.

These frameworks support all the features(such as code-splitting, routing, data fetching, and generating HTML) you need to deploy, and scale your app in production, and are working towards supporting our full-stack architecture vision.

Production-grade React frameworks:

  1. Next.js (Pages Router): npx create-next-app@latest
  2. Remix: npx create-remix
  3. Gatsby: npx create-gatsby
  4. Expo(for native apps): npx create-expo-app
  5. Bleeding-edge React frameworks
  6. Next.js (App Router): npx create-next-app@latest my-app –experimental-app

Next.js’ Pages Router is a full-stack React framework. If you’re new to Next.js, check out the learn Next.js course. Next.js is maintained by Vercel. You can deploy a Next.js app to any Node.js or serverless hosting, or to your own server. Next.js also supports a static export which doesn’t require a server.

Remix is a full-stack React framework with nested routing. It lets you break your app into nested parts that can load data in parallel and refresh in response to the user actions. If you’re new to Remix, check out the Remix blog tutorial (short) and app tutorial (long). Remix is maintained by Shopify. When you create a Remix project, you need to pick your deployment target. You can deploy a Remix app to any Node.js or serverless hosting by using or writing an adapter.

Gatsby is a React framework for fast CMS-backed websites. Its rich plugin ecosystem and its GraphQL data layer simplify integrating content, APIs, and services into one website. If you’re new to Gatsby, check out the Gatsby tutorial. Gatsby is maintained by Netlify. You can deploy a fully static Gatsby site to any static hosting. If you opt into using server-only features, make sure your hosting provider supports them for Gatsby.

Expo is a React framework that lets you create universal Android, iOS, and web apps with truly native UIs. It provides an SDK for React Native that makes the native parts easier to use. If you’re new to Expo, check out the Expo tutorial. Expo is maintained by Expo (the company). Building apps with Expo is free, and you can submit them to the Google and Apple app stores without restrictions. Expo additionally provides opt-in paid cloud services.

Next.js’s App Router is a redesign of the Next.js APIs aiming to fulfill the React team’s full-stack architecture vision. It lets you fetch data in asynchronous components that run on the server or even during the build.
Next.js is maintained by Vercel. You can deploy a Next.js app to any Node.js or serverless hosting, or to your own server. Next.js also supports static export which doesn’t require a server.

二、框架具体对比

每个生产级React框架都有不同的用途和独特的功能。以下是详细的比较:

1. Next.js(Pages Router)

适用于SSR、SSG和混合应用。

  • 命令: npx create-next-app@latest
  • 用途: 服务端渲染(SSR)、静态站点生成(SSG)和客户端渲染(CSR)。
  • 主要特性:
    • 基于文件的路由。
    • 自动代码分割。
    • 内置API路由。
    • 静态和动态渲染。
    • 增量静态再生。
    • 支持全栈开发。
    • 快速刷新(Fast Refresh)用于快速开发。
  • 使用场景: 适用于各种Web应用、博客、电商和需要SSR的复杂Web应用。

2. Remix

注重快速用户体验和流畅导航。

  • 命令: npx create-remix
  • 用途: 通过优化页面加载速度和流畅过渡来提升用户体验。
  • 主要特性:
    • 以速度为重点的服务端渲染。
    • 嵌套路由和布局。
    • 内置数据加载和动作处理。
    • 渐进增强。
    • 支持静态和动态渲染。
    • 细粒度缓存控制。
  • 使用场景: 需要快速加载和流畅导航的应用、内容丰富的网站、具有复杂路由的动态应用。

3. Gatsby

适合性能和SEO要求高的静态站点。

  • 命令: npx create-gatsby
  • 用途: 以性能和SEO为重点的静态站点生成。
  • 主要特性:
    • 从任何来源获取数据(GraphQL)。
    • 图片优化。
    • 插件生态系统。
    • 丰富的插件和主题支持。
    • 预渲染HTML以实现快速初始加载。
    • 渐进式Web应用(PWA)功能。
  • 使用场景: 博客、营销网站、文档站点,以及任何需要SEO和高性能的网站。

4. Expo(用于原生应用)

最适合快速构建跨平台移动应用。

  • 命令: npx create-expo-app
  • 用途: 构建适用于iOS和Android的React Native应用。
  • 主要特性:
    • 管理和裸工作流选项。
    • 无线更新(Over-the-air updates)。
    • 通过Expo SDK访问原生API。
    • 简单易用,快速上手。
    • 测试和调试工具。
  • 使用场景: 需要快速在iOS和Android上部署,并访问设备原生功能的移动应用。

5. Next.js(App Router)

Next.js 的 App Router 是在 Next.js 13 中引入的新特性,它提供了一种更灵活、更强大的路由方式,旨在改进和替代传统的 Pages Router。以下是对 Next.js App Router 的详细说明和与传统 Pages Router 的比较:

Next.js App Router

主要特性
  1. 文件夹级别路由(Folder-based Routing):
    • 使用文件夹结构来定义应用程序的路由,而不是单纯的文件。
    • 支持嵌套路由和布局。

目录结构:

/app
  /dashboard
    /settings
      page.tsx
    layout.tsx
  /about
    page.tsx
  layout.tsx
  page.tsx

app/page.tsx:

export default function HomePage() {
  return 

Home Page

; }

app/about/page.tsx:

export default function AboutPage() {
  return 

About Page

; }
  1. 布局(Layouts)和嵌套布局(Nested Layouts):
    • 允许在不同层级定义布局文件,实现复杂页面结构。
    • 布局文件可以共享状态和 UI 组件,简化应用结构。

app/layout.tsx:

export default function RootLayout({ children }) {
  return (
    
      
      
        
Global Header
{children} ); }

app/dashboard/layout.tsx:

export default function DashboardLayout({ children }) {
  return (
    
      
      {children}
    
  );
}
  1. 服务器组件(Server Components):
    • 提供了一种新的组件类型,仅在服务器端渲染,提高性能和安全性。
    • 可以直接在组件中获取数据,而无需在客户端进行额外的数据获取。

app/dashboard/settings/page.tsx:

export const revalidate = 60; // Revalidate data every 60 seconds

export default async function SettingsPage() {
  const data = await fetchData();
  return {data};
}

async function fetchData() {
  const res = await fetch('https://api.example.com/data');
  const json = await res.json();
  return JSON.stringify(json);
}
  1. 并行路由(Parallel Routing):
    • 允许在同一页面内定义多个并行路由,增强用户体验。
    • 适用于需要同时加载多个部分的复杂页面。

并行路由(Parallel Routing)是 Next.js App Router 的一个强大特性,它允许在同一个页面中同时显示多个独立的内容区域,这些区域可以通过不同的路径进行渲染。通过并行路由,你可以更灵活地管理复杂的页面布局,提升用户体验。

假设我们有一个页面,它需要同时显示两个独立的内容区域:一个用于显示用户信息,另一个用于显示通知。这两个区域可以独立加载和渲染。

目录结构

/app
  /parallel
    @user
      page.tsx
    @notifications
      page.tsx
  layout.tsx
  page.tsx

并行路由布局文件

app/layout.tsx:

export default function RootLayout({ children }) {
  return (
    
      
      {children}
    
  );
}

app/parallel/layout.tsx:

export default function ParallelLayout({ user, notifications }) {
  return (
    
      {user}
      {notifications}
    
  );
}

并行路由内容页面

app/parallel/@user/page.tsx:

export default function UserPage() {
  return User Information;
}

app/parallel/@notifications/page.tsx:

export default function NotificationsPage() {
  return Notifications;
}

主页面文件

app/page.tsx:

import Link from 'next/link';

export default function HomePage() {
  return (
    
      

Home Page

Go to Parallel Page ); }

工作原理

  • app/parallel/@user/page.tsxapp/parallel/@notifications/page.tsx 定义了两个独立的内容区域。
  • app/parallel/layout.tsx 用于渲染这两个区域。
  • app/parallel/layout.tsx 文件中,usernotifications 是并行路由插槽。
  • 这些插槽分别渲染 app/parallel/@user/page.tsxapp/parallel/@notifications/page.tsx 文件的内容。
  • 当用户访问 /parallel 路由时,ParallelLayout 会同时渲染 UserPageNotificationsPage,并在页面中显示它们的内容。

并行路由允许在同一页面中并行渲染多个独立的内容区域,这在构建复杂的用户界面时非常有用。通过这种方式,你可以更高效地管理页面布局,提高应用的可维护性和用户体验。

  1. 界面隔离(Isolated Interfaces):
    • 使用新的界面隔离机制,防止组件之间的意外依赖和副作用。
    • 提高组件的可维护性和可测试性。

app/dashboard/settings/page.tsx:

'use client';

import { useState } from 'react';

export default function SettingsPage() {
  const [setting, setSetting] = useState('');

  const handleChange = (e) => {
    setSetting(e.target.value);
  };

  return (
    
      
      

Current setting: {setting}

); }

示例代码通过定义单独的文件并使用严格的组件分离。

  1. 全新的数据获取机制:
    • 支持 fetch 和其他数据获取方法直接在服务器组件中使用。
    • 提供了更灵活的数据获取方式。

app/dashboard/settings/page.tsx:

export default async function SettingsPage() {
  const data = await fetchData();
  return {data};
}

async function fetchData() {
  const res = await fetch('https://api.example.com/data', {
    next: { revalidate: 60 }
  });
  const json = await res.json();
  return JSON.stringify(json);
}
与 Pages Router 的对比
  • 文件结构:

    • Pages Router: 基于文件的路由,页面文件直接放置在 pages 目录中。
    • App Router: 基于文件夹的路由,使用 app 目录,路由通过文件夹结构定义,支持更复杂的布局和路由结构。
  • 布局管理:

    • Pages Router: 需要在每个页面中手动引入布局组件。
    • App Router: 使用布局文件夹,自动应用布局,支持嵌套布局。
  • 服务器组件:

    • Pages Router: 主要使用客户端组件,数据获取通常在 getServerSidePropsgetStaticProps 中完成。
    • App Router: 引入服务器组件,允许在服务器端直接进行数据获取,提高性能和安全性。
  • 并行路由:

    • Pages Router: 需要手动管理并行路由和状态。
    • App Router: 提供内置支持,更容易实现复杂的页面结构。

具体使用示例

创建 App Router 项目
npx create-next-app@latest my-app --experimental-app
cd my-app
目录结构示例
/app
  /dashboard
    /settings
      page.tsx
    layout.tsx
  /about
    page.tsx
  layout.tsx
  page.tsx
  • app/layout.tsx: 顶级布局文件,应用于所有页面。
  • app/page.tsx: 应用的主页。
  • app/dashboard/layout.tsx: 仪表板的布局,应用于仪表板下的所有页面。
  • app/dashboard/settings/page.tsx: 仪表板设置页面。
示例代码

app/layout.tsx:

export default function RootLayout({ children }) {
  return (
    
      
      {children}
    
  );
}

app/dashboard/layout.tsx:

export default function DashboardLayout({ children }) {
  return (
    
      
      {children}
    
  );
}

app/dashboard/settings/page.tsx:

export default function SettingsPage() {
  return 

Dashboard Settings

; }

总结

Next.js 的 App Router 提供了更强大的路由和布局管理功能,通过引入服务器组件、并行路由和新的数据获取机制,使得开发复杂的 React 应用更加高效和灵活。对于希望利用这些新特性构建现代化 Web 应用的开发者来说,App Router 是一个值得探索和使用的工具。

本站无任何商业行为
个人在线分享 » WHAT – React 学习系列(二)
E-->