gpt4 book ai didi

reactjs - 测试中的 ReactDOM.unmountComponentAtNode() 导致警告

转载 作者:行者123 更新时间:2023-12-03 13:33:53 29 4
gpt4 key购买 nike

我通过 create-react-app 构建了我的应用程序。在它的最新版本中,它在 Jest 的引导测试设置中添加了一行来卸载组件(请参阅 ReactDOM.unmountComponentAtNode(div))。

import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});

当我为我的应用程序组件运行测试时,它会导致警告。

警告:只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了 setState、replaceState 或forceUpdate。这是一个空操作。

我的猜测:发生这种情况是因为我在 componentDidMount() 中有一个异步请求:

fetchFoo(bar) {
fetch(SOME_URL)
.then(response => response.json())
.then(result => this.setState({ result }))
.catch(error => this.setState({ error }));
}

如果是这种情况,我如何在测试中等待异步请求最终再次卸载组件?我知道我可以删除 Jest 测试中导致此问题的一个衬里,但我想修复它。

解决方案:解决了该问题并记录了如何解决该问题 here .

最佳答案

解决此问题的最简单方法是让您的 fetch() 在组件卸载时正确取消自身。在 componentDidMount() 中拥有不会自行取消的异步请求在 React 中是不好的做法,因为根据网络速度和 UI 交互,它们可能会频繁尝试更新未安装组件的状态。使用可取消的 Promise,或者使用 this.shouldCancel 实例变量来指示天气是否调用 setState(),如下所示:

class LifecycleTest extends React.Component {
constructor(props){
super(props)
this.shouldCancel = false;
this.state = {
result:null,
err:null
}
}

componentDidMount(){
asyncTask()
.then(result => !this.shouldCancel ? this.setState({result}) : null)
.catch(err => !this.shouldCancel ? this.setState({err}) : null);
}

componentWillUnmount(){
this.shouldCancel = true
}

render(){
const {err, result} = this.state
if(err){
return <div className="err">{err}</div>
}else if (result){
return <div className="result">{result}</div>
}else{
return <div className="loading">Loading...</div>
}
}
}

( view on webpackbin )

也就是说,如果您确实想在不更改源代码的情况下通过此测试,您可以模拟 fetch() 以返回一个永远不会解析的“dud”Promise 。例如,添加此内容应该可以修复错误:

window.fetch = jest.fn(() => new Promise((accept, reject) => {}))

然而,这是一个可怕的黑客攻击。更好的解决方案是在组件卸载时正确取消网络请求。

关于reactjs - 测试中的 ReactDOM.unmountComponentAtNode() 导致警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48623313/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com