首页 >web前端 >js教程 >在 React Hooks 应用程序中利用 Web Worker 进行后台处理。

在 React Hooks 应用程序中利用 Web Worker 进行后台处理。

WBOY
WBOY原创
2024-07-24 21:09:511099浏览

1.0 简介

React 中的 Web Workers 是允许在 React 应用程序中并发运行多个线程的函数。它允许某些线程在后台运行,以排除其作为主线程的一部分运行。

例如,您有一个应用程序,您可能想要执行复杂的计算、从 API 获取大数据或实现后台通知,而不改变当前运行的主线程的正常功能。这可以通过实现 React Web Hooks 来实现,确保当所有这些进程在 React 应用程序中运行时用户界面不会冻结。

在本指南中,我们将创建一个示例 React 项目,该项目在自定义 React hook 中实现 Web Worker 来执行指数计算。

步骤

第 1 步:创建 React 应用程序

创建一个反应应用程序。

npx create-vite myproject -- --template react

我更喜欢使用 vite 创建 React 应用程序,因为与 create-react-app 相比,它的运行时间更快。
这里我们使用vite中的react作为模板。

Select React as your template

选择 JavaScript:

Select Variant as JavaScript

Utilizing Web Workers for Background Processing in React Hooks Applications.

在编辑器上打开项目。 (我将在这个项目中使用 Vs code)

code .

第 2 步:搭建我们的项目。

在 src 目录中,创建另一个目录 hooks/useWebWorkers。
在此文件夹中,创建一个 index.js 文件来保存我们的 Web Worker,如下所示:

Utilizing Web Workers for Background Processing in React Hooks Applications.

第 3 步:创建我们的网络工作者

在 /hooks/useWebWorker/index.js 中,我们创建一个自定义挂钩,用于创建我们的 Web Worker

创建一个 useWebWorker 自定义钩子,以workerFunction 和 inputData 作为参数。

const useWebWorker =(workerFunction,inputData)=>{

}
export default useWebWorker;

使用 useState 钩子初始化我们的结果、错误和 Web Worker 状态的状态。

import {useState} from 'react'
const useWebWorker =(workerFunction,inputData)=>{
const [result,setResult] = useState(null);
const [error,setError] = useState(null);
const [loading,setLoading] = useState(false);

}
export default useWebWorker;

i) result 存储我们网络工作者的结果。初始设置为 null。

ii)error 跟踪 Web Worker 中可能发生的错误。最初设置为 null。

iii) 加载给出了我们的 Web Worker 的状态,无论它是否正在处理数据。最初设置为 false。

初始化 useEffect 来保存我们的 Web Worker。

import {useState,useEffect} from 'react'
const useWebWorker =(workerFunction,inputData)=>{
const [result,setResult] = useState(null);
const [error,setError] = useState(null);
const [loading,setLoading] = useState(false);

useEffect(()=>{

},[inputData])

}
export default useWebWorker;

只要 inputData 发生变化,useEffect 钩子就会运行,因为它已被设置为分隔符,
当 inputData 为 null 或未定义时,钩子提前退出。

if(!inputData)return;

确保所有状态都正确重置

    setLoading(true);
    setError(null);
    setResult(null);

创建一个 Web Worker Blob

    const blob = new Blob(
      [
        `
          self.onmessage = function(event) {
            (${workerFunction.toString()})(event);
          };
        `,
      ],
      { type: "application/javascript" }
    );

将workerFunction 转换为字符串并将其包含在Blob 对象中。此Blob 表示将在Web Worker 中运行的JavaScript 代码。

创建一个为 Blob 生成 URL 的 Worker,并使用此 URL 创建一个新的 Web Worker:

    const workerScriptUrl = URL.createObjectURL(blob);
    const worker = new Worker(workerScriptUrl);

为工作人员发出的消息设置事件处理程序。

worker.onmessage(event){

}

当 Web Worker 向主线程发送消息(使用 postMessage)时,会触发事件处理程序。
event.data 包含 Web Worker 中的有效结果或错误。我们处理 if-else 语句中错误或有效结果的呈现。

如果出现错误,我们将错误设置为 setError() 内的 event.data.error。
如果返回有效结果,我们将结果传递给 setResult()
内的 event.data

    worker.onmessage = (event) => {
      console.log("Worker result:", event.data);
      if (event.data.error) {
        setError(event.data.error);
      } else {
        setResult(event.data);
      }
      setLoading(false);
    };

完成后将加载设置为 false。

处理 Web Worker 错误:

我们使用worker.onerror(event){

}
我们将 event 作为参数传递,将错误更新为 event.message 并将加载状态更新为 false。

    worker.onerror = (event) => {
      console.error("Worker error:", event.message);
      setError(event.message);
      setLoading(false);
    };

我们现在将 inputData 发送给网络工作者

worker.postMessage(inputData);

当组件卸载或 inputData 或workerFunction 更改时,我们终止 Web Worker 并撤销 Blob URL:

    return () => {
      worker.terminate();
      URL.revokeObjectURL(workerScriptUrl);
    };
  }, [inputData, workerFunction]);

我们最终通过返回结果、错误和加载状态来返回 Web Worker 的状态:

return {result,error,loading}

导出 useWebWorker:

export default useWebWorker;

下面是hooks/useWebWorker/index.js的完整代码:

import { useState, useEffect } from "react";

const useWebWorker = (workerFunction, inputData) => {
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!inputData) return;

    setLoading(true);
    setError(null);
    setResult(null);

    const blob = new Blob(
      [
        `
          self.onmessage = function(event) {
            (${workerFunction})(event);
          };
        `,
      ],
      { type: "application/javascript" }
    );

    const workerScriptUrl = URL.createObjectURL(blob);
    const worker = new Worker(workerScriptUrl);

    worker.onmessage = (event) => {
      console.log("Worker result:", event.data);
      setResult(event.data);
      setLoading(false);
    };

    worker.onerror = (event) => {
      console.error("Worker error:", event.message);
      setError(event.message);
      setLoading(false);
    };

    console.log("Posting message to worker:", inputData);
    worker.postMessage(inputData);

    return () => {
      worker.terminate();
      URL.revokeObjectURL(workerScriptUrl);
    };
  }, [inputData, workerFunction]);

  return { result, error, loading };
};

export default useWebWorker;

第 4 步:编辑我们的 App.jsx

在我们的 App.jsx 中,我们定义一个将由我们的 Web Worker 执行的工作函数:

const workerFunction = (e) => {
  const { base, exponent } = e.data;
  console.log("Worker function received data:", base, exponent);

  let result = 1;
  for (let i = 0; i < exponent; i++) {
    result *= base;
  }

  self.postMessage(result);
};

e.data contains data from the web worker.

The workerFunction:
Logs the received data (base and exponent).
Computes the power of base raised to exponent.
Sends the result back to the main thread using self.postMessage(result).

Let's now define our App functional component inside our App.jsx:

const App = () => {
  const [base, setBase] = useState("");
  const [exponent, setExponent] = useState("");
  const [inputData, setInputData] = useState(null);
  const { result, error, loading } = useWebWorker(workerFunction, inputData);

base: Stores the base number input.
exponent: Stores the exponent number input.
inputData: Stores the data to be sent to the worker.
Custom Hook Usage: useWebWorker is used to create a Web Worker and manage its state.

  const handleBaseChange = (e) => setBase(e.target.value);
  const handleExponentChange = (e) => setExponent(e.target.value);

handleBaseChange: Updates base state when the input value changes.
handleExponentChange: Updates exponent state when the input value changes

  const handleCalculate = () => {
    setInputData({ base: Number(base), exponent: Number(exponent) });
  };

handleCalculate Function: Converts base and exponent to numbers and sets them as inputData for the Web Worker.

  return (
    <div>
      <h1>Exponential Calculation with Web Worker</h1>
      <div>
        <label>
          Base:
          <input type="number" value={base} onChange={handleBaseChange} />
        </label>
      </div>
      <div>
        <label>
          Exponent:
          <input type="number" value={exponent} onChange={handleExponentChange} />
        </label>
      </div>
      <button onClick={handleCalculate}>Calculate</button>
      {loading && <div>Loading...</div>}
      {error && <div>Error: {error}</div>}
      {!loading && !error && result !== null && <div>Result: {result}</div>}
    </div>
  );
};

JSX Layout:
Displays a title and input fields for base and exponent.
A button triggers the handleCalculate function.
Conditionally renders loading, error, or result messages based on the state.

Below is the complete App.jsx code:

import { useState } from "react";
import useWebWorker from "./hooks/useWebWorker";
import "./App.css";

const workerFunction = (e) => {
  const { base, exponent } = e.data;
  console.log("Worker function received data:", base, exponent);

  let result = 1;
  for (let i = 0; i < exponent; i++) {
    result *= base;
  }

  self.postMessage(result);
};

const App = () => {
  const [base, setBase] = useState("");
  const [exponent, setExponent] = useState("");
  const [inputData, setInputData] = useState(null);
  const { result, error, loading } = useWebWorker(workerFunction, inputData);

  const handleBaseChange = (e) => setBase(e.target.value);
  const handleExponentChange = (e) => setExponent(e.target.value);

  const handleCalculate = () => {
    setInputData({ base: Number(base), exponent: Number(exponent) });
  };

  return (
    <div>
      <h1>Exponential Calculation with Web Worker</h1>
      <div>
        <label>
          Base:
          <input type="number" value={base} onChange={handleBaseChange} />
        </label>
      </div>
      <div>
        <label>
          Exponent:
          <input type="number" value={exponent} onChange={handleExponentChange} />
        </label>
      </div>
      <button onClick={handleCalculate}>Calculate</button>
      {loading && <div>Loading...</div>}
      {error && <div>Error: {error}</div>}
      {!loading && !error && result !== null && <div>Result: {result}</div>}
    </div>
  );
};

export default App;

We can now use npm run dev to view our project.
Below is a live preview of our project:
Web Workers Project Implementation

Conclusion

Implementing Web Workers in your React applications can significantly enhance performance, especially when dealing with CPU-intensive tasks. By offloading such tasks to background threads, you ensure that your app remains responsive and provides a smooth user experience.

In our example, we've seen how straightforward it can be to set up and use Web Workers in a React environment. From dynamically creating a worker using a custom hook to managing the communication between the main thread and the worker, every step is designed to be both efficient and easy to integrate.

This approach not only helps in maintaining a responsive UI but also makes your app more robust and user-friendly. Whether it's for complex calculations, data processing, or any other heavy lifting, Web Workers can be your go-to solution for multitasking in modern web applications.

Remember, the key to a great user experience is not just about what your app does but how it feels while doing it. By implementing Web Workers, you can ensure that your app feels snappy and responsive, keeping your users happy and engaged. So, go ahead and explore the power of Web Workers in your next React project – your users will thank you for it!

以上是在 React Hooks 应用程序中利用 Web Worker 进行后台处理。的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn