我做了一个浏览器扩展,将iframe注入到其中包含html的DOM中。我一直在尝试将React组件渲染到iframe中,但无法渲染,并且收到以下错误Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
我尝试通过内容脚本同时渲染到iframe甚至直接渲染到DOM,但是我仍然遇到同样的问题。我知道正在调用组件的render函数,因为我在其中放置了console.log并显示了消息;我还调试了它,并且断点在render函数中停止了。另外,我添加了生命周期方法componentWillUpdate
和componentDidUpdate
,甚至没有调用它们。
//Index.jsx
import React from "react";
import ReactDOM from "react-dom";
class Index extends React.Component{
constructor(props){
super(props);
}
componentWillUpdate(){
console.log('componentWillUpdate');
}
componentDidUpdate(){
console.log('componentDidUpdate');
}
render() {
console.log('render');
return <div>Hello!</div>;
}
}
ReactDOM.render(<Index/>, document.getElementById("g-root"))
// Including this code to show how I was adding the react component to the DOM if it is loaded immediately via manifest.json
// const app = document.createElement('div');
// app.id = "g-root";
// document.body.appendChild(app);
// ReactDOM.render(<Index />, app);
//webpack.config
const path = require('path');
module.exports = (env, args) => {
return {
mode,
devtool,
entry: {
react: path.join(__dirname, './Index.jsx')
},
module: {
rules: [{
test: /\.jsx$/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react', 'es2015']
}
}
}]
},
output: {
path: path.join(__dirname, './'),
filename: 'react.bundle.js'
}
}
};
<!--This gets loaded into the iframe-->
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="g-root"></div>
<script src="react/react.bundle.js"></script>
</body>
</html>
//manifest.json *included just to show that it has the same issue on page load.
{
"content_scripts":
[{
"js":["react/react.bundle.js"],
"run_at": "document_end",
"matches": ["<all_urls>"]
}]
}
应该注意的是,注入iframe以及整个扩展都可以正常工作,直到我开始尝试将React添加到项目中为止。
答案 0 :(得分:0)
事实证明这是一个内部库的问题,该库与用我的React组件渲染Web组件有关。