Javascript 未捕获错误:对象作为React子对象无效(找到:[object HTMLImageElement])
在reactjs中,如何在道具更改时动态更新二维码组件。我正在使用这个npm包:Javascript 未捕获错误:对象作为React子对象无效(找到:[object HTMLImageElement]),javascript,reactjs,Javascript,Reactjs,在reactjs中,如何在道具更改时动态更新二维码组件。我正在使用这个npm包: componentWillMount()函数正在第一次加载时工作,但它没有得到更新,但如果我渲染{this.state.el},则我会得到:*react dom.development.js:57未捕获错误:对象作为react子对象无效(找到:[object HTMLImageElement])。如果要呈现子对象集合,请改用数组* ``` 从“React”导入React,{Component}; 从“kjua”进
componentWillMount()
函数正在第一次加载时工作,但它没有得到更新,但如果我渲染{this.state.el}
,则我会得到:*react dom.development.js:57未捕获错误:对象作为react子对象无效(找到:[object HTMLImageElement])
。如果要呈现子对象集合,请改用数组*
```
从“React”导入React,{Component};
从“kjua”进口kjua;
类QRCODEONAMOUNTEXTENDS组件{
建造师(道具){
超级(道具);
此.state={
艾尔:克鲁亚({
案文:`数额=${
这个.props.text
}&备忘录=xxxx`
}),
金额:this.props.text
};
}
组件willmount(){
document.querySelector('body').appendChild(this.state.el);
}
render(){
返回(
QRCODEONAMOUNT输入的金额:{this.props.text}
在此处打印QRCode:{this.state.el}
);
}
}
输入导出默认QRCODEONA```代码>将道具保存到状态是一种反反应模式(在道具.text
=>此.state.amount
)的情况下,不建议使用组件willmount
,而是使用组件didmount
在组件安装后产生副作用
我试着看了kjua的文档,但似乎很过时。我假设您向它传递一些“文本”,它会返回该文本的二维码图像。在react中似乎不可渲染为对象,但可能,src
将允许您将其渲染为
标记
QRCODEONAMOUNT输入的金额:{this.props.text}
必须是无效的
。得到同样的错误谢谢Drew!componentDidUpdate导致循环:超出最大更新深度。当组件在componentWillUpdate或componentDidUpdate内重复调用setState时,可能会发生这种情况。React限制嵌套更新的数量以防止无限循环。这就是为什么您必须使用条件测试仅在新状态或属性值到达时设置状态。这不是我已经使用的条件:componentDidUpdate(prevState,prevProps){if(prevProps.amount!==this.props.text){const newQRcode=kjua({text:amount=${this.props.text}&memo=xxxx
});console.log(prevProps.amount);console.log(this.props.text);console.log(newQRcode);this.setState({el:newQRcode});}console.log(“比较失败”);}amount
从来都不是我能告诉你的道具值,所以prevProps.amount!==this.props.text
将始终计算为true。你只需在构造函数中设置this.state.amount
。注意,它在this.state
中。如果你想让你的支票是prevState.amount!==this.props.text
,那么你就可以使用它,然后,您还需要将this.props.text
存储到this.state.amount
中,以便只有当新的props.text
进入时,条件才会计算为true。不过,将道具保存到state是一种反模式,这就是为什么您可以将prevProps
与当前的this.props
进行比较。太棒了hanks Drew。它正在工作。我遵循下面的正确标准吗?构造函数(props){super(props);this.state={el:null,amount:this.props.amount};}componentDidUpdate(prevState,prevProps){if(prevProps.amount!==this.props.amount){const newQRcode=kjua({text:amount=${this.props.amount}&memo=xxxx
});console.log(prevProps.amount);console.log(this.props.amount);//console.log(newQRcode);this.setState({el:newQRcode,amount:this.props.amount});}
render() {
const { el } = this.state;
return (
<React.Fragment>
QrCodeOnAmountEntered amount: {this.props.text}
<p>Print QRCode here:</p>
{el && <img src={el.src}/>}
</React.Fragment>
);
}
componentDidUpdate(prevState, prevProps) {
// if current text value is not equal to the previous, calculate
// and save new QR code image in el, else ignore
if (prevProps.text !== this.props.text) {
const newQRcode = kjua({ text: `amount=${this.props.text}&memo=xxxx` });
this.setState({ el: newQRcode });
}
}