简体   繁体   中英

How to use "vanilla" WebWorker in React?

How do I use webworkers in a react app ?

I wrote an webworker and tested it in a simple app (html) so it works fine.

But using same approach in a react app doesnt work

I don't want at first use any react-something-webworker, I want just use pure Work api

const _worker = new Worker('./worker')

seems not importing the code inside worker.js file (self.addEventListener("message...)

Thanks for helping

In a React class component you can instantiate a web worker in componentDidMount , define the worker's onmessage and onerror methods, then call worker.terminate() in componentWillUnmount .

In a React function component, replace componentDidMount and componentWillUnmount with useEffect .

Your React component and your worker can then exchange messages with postMessage .


Even if you don't want to use any React-specific libraries, have a look at the code from the react-hooks-worker library. It's less than 100 LOC and it will help you understand how to use the Web Worker API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM