如何使用三个有用的工具提升你的 React 技能

自 2013 年发布以来,React.js 一直是使用最广泛的 JavaScript 工具之一,这要归功于其无与伦比的多功能性和效率。

在其基于组件的架构和虚拟 DOM 实现的支持下,React.js 在构建现代动态 Web 应用程序方面表现出色。它使开发人员能够创建可重用的 UI 元素,从而提高生产力。

由于其广泛的工具和强大的生态系统,React.js 仍然是无数开发人员的首选库,为众多网站和应用程序提供支持。

但快速发展的 React 生态系统可能会给开发人员带来挑战,尤其是那些新手。本文将提供有关 React 生态系统中强大工具的见解和信息。它的目的是帮助您提高技能并在 React 开发领域保持领先地位。

通过随时了解最新工具,您可以更有效地驾驭 React 生态系统并改进您的开发过程。
用于状态管理的 Recoil.js
什么是 Recoil.js?
Recoil.js 是 Facebook 开发的开源状态管理库。与 Redux、MobX、Zustand 等其他状态管理库相比,它具有明显的优势。

Recoil 的主要优势在于其简单性、灵活性、调试支持以及与现有项目的兼容性。这些功能以及更多功能使 Recoil 成为 React 应用程序中管理状态的首选。

Recoil.js 的主要特点
Recoil 有两个关键特性有助于其在状态管理方面的有效性。

原子
Recoil.js 中的 Atom 是 React 组件可以读取和写入的可共享状态。订阅的组件可以访问和修改 Atom 的值(数据)。

下面的代码块显示了 Atom 定义的示例:


import React from 'react'; // Importing the React library

import { atom } from 'recoil'; // Importing the 'atom' function from the Recoil library

// Define the Atom
const counter = atom({ // Defining an Atom called 'counter'
  key: 'count', // Unique identifier for the Atom
  default: 0, // Initial value of the Atom is set to 0
});

export default counter; // Exporting the 'counter' Atom as the default export of the module

上面的代码显示了如何使用 Recoil。counter它定义了一个使用 Recoil 提供的函数调用的 Atom atom。Atom 的唯一标识符设置为“计数”,默认值设置为 0。然后导出 Atom,使其可供其他组件访问以使用和管理状态。

定义一个 Atom 后,可以在其他 React Components 中共享和使用:

import React from 'react'; // Importing the React library

import { useRecoilValue } from 'recoil'; // Importing the 'useRecoilValue' hook from the Recoil library

import { counter } from './atom'; // Importing the 'counter' Atom from the './atom' file

function CounterComponent() { // Declaring a functional component named 'CounterComponent'
  const count = useRecoilValue(countAtom); // Using the 'useRecoilValue' hook to get the current value of the 'countAtom' Atom

  return (
    <div>
      <h1>Count: {count}</h1> {/* Displaying the value of 'count' in the component's UI */}
    </div>
  );
}

上面的代码块演示了 Recoil Atom 在CounterComponent. useRecoilValue它从 Recoil 库和Atom导入钩子counter。使用CounterComponent挂钩useRecoilValue检索counterAtom 的当前值。然后它会在组件的元素中显示“count”的值h1。

选择器
Recoil.js 还包含选择器,使开发人员能够根据现有状态数据同步或异步地转换或改变状态。

Recoil 中的选择器提供了一种强大的机制来操纵状态并促进基于 Recoil 的应用程序中的高级数据转换。

Recoil 选择器大放异彩的一个用例是在需要不断更新的应用程序中,例如购物车应用程序。

假设我们有一个名为 Recoil 的原子cartItems,它存储添加到购物车中的项目数组。购物车中的每件商品都具有id、 price和 等属性quantity。

我们可以定义一个名为 Recoil 的选择器totalPriceSelector,它根据商品的数量和价格计算购物车中所有商品的总价。这是一个例子:

import { selector, useRecoilValue } from 'recoil'; // Importing the 'selector' and 'useRecoilValue' from Recoil library

import { cartItems } from './atom'; // Importing the 'cartItems' Atom from the './atom' file

const totalPriceSelector = selector({ // Defining a selector called 'totalPriceSelector'
  key: 'totalPrice', // Unique identifier for the selector
  get: ({ get }) => { // 'get' function that calculates the total price based on the cart items
    const items = get(cartItems); // Getting the value of the 'cartItems' Atom
    let total = 0; // Initializing the total price

    items.forEach(item => { // Iterating over the items in the cart
      total += item.price * item.quantity; // Calculating the total price based on item prices and quantities
    });

    return total; // Returning the calculated total price
  },
});

function ShoppingCart() { // Declaring a functional component named 'ShoppingCart'
  const totalPrice = useRecoilValue(totalPriceSelector); // Using the 'useRecoilValue' hook to get the value of 'totalPriceSelector'

  return (
    <div>
      <h2>Shopping Cart</h2>
      <p>Total Price: ${totalPrice}</p> // Displaying the total price in the component's UI
    </div>
  );
}


在上面的示例中,通过使用 Recoil 选择器,我们可以根据购物车商品的当前状态轻松推导和更新总价。这允许采用反应式且高效的方法来管理购物车应用程序中的复杂状态转换。

用于数据获取的 SWR(陈旧-重新验证)
什么是驻波比?
SWR 是一种 React 工具,它使用一种称为 Stale-While-Revalidate 的强大数据获取技术。它向用户提供缓存(陈旧)数据,同时发起刷新或重新验证数据的请求。

随着时间的推移,开发人员一直在争论最有效的数据检索方法以及如何消除加载数据所需的等待时间。通过在 React 中利用 SWR,您可以优化性能、最小化网络请求,并通过在后台更新数据的同时显示即时数据来为用户提供无缝体验。

由于其简单性和灵活性,SWR 已成为 React 中处理复杂数据获取的流行选择。

SWR的关键部件
Stale While Revalidate Strategy: SWR 向用户提供缓存数据,同时发起请求以在后台重新验证数据。这减少了页面加载时间
自动缓存: SWR 包含一个内置的缓存机制,可以自动存储和检索获取的数据。这允许从缓存中提供对相同数据的后续请求。
自动重新验证: SWR 根据开发人员设置的某些条件自动重新验证陈旧数据——例如,当组件被聚焦、挂载时等。
useSWR Hook: 这个钩子是在 React 中使用 SWR 的主要接口。它接受一个配置参数并返回一个带有data、error和isValidating键的对象。
依赖跟踪: SWR 跟踪数据获取函数的依赖关系,并在因变量发生变化时自动重新验证数据
如何在 React 应用中实现 SWR
下面是一个在页面上获取和加载数据的简单 React 组件中 SWR 实现的示例:

import React from 'react'; // Importing React library

import useSWR from 'swr'; // Importing the useSWR hook from the SWR library

const fetchData = async (url) => {
  const response = await fetch(url); // Making an HTTP request to the provided URL
  const data = await response.json(); // Parsing the response data as JSON
  return data; // Returning the fetched data
};

function MyComponent() {
  const { data, error, isValidating } = useSWR('https://api.example.com/data', fetchData, {
    refreshInterval: 3000, // Refresh data every 3 seconds
    revalidateOnFocus: True, // enable revalidation when the component regains focus
  });

  if (error) {
    return <p>Error occurred: {error.message}</p>; // Displaying an error message if an error occurred during data fetching
  }

  if (!data) {
    return <p>Loading...</p>; // Displaying a loading indicator while data is being fetched
  }

  return (
    <div>
       <h1>Data: {data}</h1> // Displaying the fetched data
    </div>
  );
}

export default MyComponent; // Exporting the MyComponent function as the default export

useSWR上面的代码块说明了SWR 库中的钩子在 React 组件中的用法。它导入必要的依赖项并定义一个调用函数fetchData以从提供的 URL 获取数据。

在函数内部MyComponent,useSWR钩子用于获取数据。该挂钩采用一些配置参数并提供三个变量:data、error和isValidating。

如果在数据获取过程中发生错误,则会显示一条错误消息。在获取数据时,会显示加载指示器。成功获取数据后,它会显示在一个

元素中。

用于集成现代表单和表单功能的 Formik
什么是福米克?
响应式表单已成为现代软件开发不可或缺的一部分,尤其是因为需要收集用户数据和记录交互。

对于 React 应用程序,Formik 是一个流行的表单管理库,它简化了构建和管理响应式表单的过程。

Formik 是高度可定制的。它的主要优势之一是字段数组功能,它允许您根据用户输入动态添加和删除表单字段。

Formik 的简单性、状态管理功能、数据验证功能、与 React 生态系统的更好集成以及更小的文件大小是许多开发人员更喜欢使用它而不是 Redux Form 的部分原因。

Formik 的关键组件
内置表单状态管理: Formik 附带内置表单状态管理功能,无需其他状态管理库。
数据验证和错误处理: Formik 提供易于集成的数据验证和错误处理功能,从而简化了响应式表单制作过程。
字段数组:FieldArray是一个 Formik 组件,用于管理表单字段数组。它为您提供了允许动态操作表单字段的功能(即,动态添加或删除字段)。
Fast Field:Fastfield是一个 Formik 组件,可防止对未更改的表单字段进行不必要的重新渲染。这种优化可以大大提高具有许多字段的大型表单的性能。
如何在 React 应用程序中实施 Formik
下面是 Formik 在组件的基本 React 中的简单实现:

import React from 'react';
import { Formik, Field, ErrorMessage, Form, resetForm } from 'formik';

function MyForm() {
  // Initial form values
  const initialValues = {
    name: '',
    email: '',
   };

  // Form validation function
  const validateForm = (values) => {
    const errors = {};

    // Check if name field is empty
    if (!values.name) {
      errors.name = 'Name is required';
    }

    // Check if email field is empty or invalid
    if (!values.email) {
      errors.email = 'Email is required';
    } else if (!/\S+@\S+\.\S+/.test(values.email)) {
      errors.email = 'Invalid email format';
    }

    return errors;
  };

  // Form submission handler
  const handleSubmit = (values, { resetForm }) => {
    // Perform form submission logic, e.g API call
    console.log(values);

    // Reset the form after successful submission
    resetForm();
  };

  return (
    <div>
      <h1>My Form</h1>
      <Formik 
        initialValues={initialValues}
        validate={validateForm}
        onSubmit={handleSubmit}
      >
        <Form>
          <div>
            <label htmlFor="name">Name:</label>
            <Field type="text" id="name" name="name" />
            <ErrorMessage name="name" component="div" />
          </div>

          <div>
            <label htmlFor="email">Email:</label>
            <Field type="email" id="email" name="email" />
            <ErrorMessage name="email" component="div" />
          </div>


          <button type="submit">Submit</button>
        </Form>
      </Formik>
    </div>
  );
}

export default MyForm;

上面的代码块演示了使用 Formik 库实现响应式表单。

该MyForm组件定义初始表单值并使用validateForm函数实现表单验证逻辑。表单提交由handleSubmit函数处理。

表单使用组件在 JSX 代码中呈现Formik,表单字段使用组件定义Field。

ErrorMessage使用Formik 提供的组件显示错误消息。

提交后,表单值将记录到控制台,并使用该resetForm函数重置表单。

结论
本文探讨了三个强大的 React.js 工具:用于状态管理的 Recoil、用于数据获取的 SWR 和用于响应式表单的 Formik。

通过使用这些工具,您可以增强您的 React.js 技能并在动态的 React 生态系统中保持领先地位。有关这些工具的更多信息,您可以查看Recoil.js 文档、SWR 文档和Formik 文档。

关注我的博客,您将在其中获得提示、技巧和挑战,以保持您的技能敏锐。记得关注我哦!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Q shen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值