React 18 警告 'act(...)' 的解决方法:ReactDOM.createRoot() VS ReactDOM.render()

在 React 18 中,使用 act(...) 函数进行测试时,可能会遇到如下警告:

Warning: The current testing environment is not configured to support act(...)

这个警告提示我们,当前的测试环境不支持 act(...) 函数。这是因为 act(...) 是 React 18 中新加入的 API,用于在测试中模拟用户交互,而低于 React 18 版本的测试环境可能不支持它。

解决方法:

ReactDOM.createRoot() 改为 ReactDOM.render()createRoot() 是 React 18 中新加入的 API,用于创建新的 root 元素。而 ReactDOM.render() 则是在 React 18 之前版本中使用的 API。

示例:

原始代码:

import React from 'react'
import ReactDOM from 'react-dom/client'
import { Appointment } from '../src/Appointment'
import { act } from 'react-dom/test-utils';

describe('Appointment', () => { 
  it('renders the customer first name', () => { 
      const customer = { firstName: 'Ashley' } 

      const container = document.createElement('div');
      document.body.replaceChildren(container);
      act(() => { 
        ReactDOM.createRoot(container).render(<Appointment customer={customer} />) 
      })
      expect(document.body.textContent).toContain( 
        'Ashley' 
      ); 
  }) 
})

修改后的代码:

import React from 'react'
import ReactDOM from 'react-dom'
import { Appointment } from '../src/Appointment'

describe('Appointment', () => { 
  it('renders the customer first name', () => { 
      const customer = { firstName: 'Ashley' } 

      const container = document.createElement('div');
      document.body.replaceChildren(container);
      ReactDOM.render(<Appointment customer={customer} />, container)
      expect(document.body.textContent).toContain( 
        'Ashley' 
      ); 
  }) 
})

总结:

使用 ReactDOM.render() 可以避免 act(...) 警告,同时保证代码在低于 React 18 的版本中也能正常运行。

React 18 警告 'act(...)' 的解决方法:ReactDOM.createRoot() VS ReactDOM.render()

原文地址: https://www.cveoy.top/t/topic/oEGc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录