【发布时间】:2018-11-24 06:23:41
【问题描述】:
我有一个IFrameComponent 组件,灵感来自this post。
基本上是这样的:
class IFrameComponent extends React.Component {
shouldComponentUpdate() {
return false;
}
componentWillReceiveProps(nextProps) {
if(this.props.content !== nextProps.content) {
const html = getHTMLFromContent();
const fdoc = this.iFrame.contentDocument;
fdoc.write(html);
}
}
render() {
return (<iframe sandbox="..." ref={f => this.iFrame = f} />);
}
}
现在componentWillReceiveProps 被认为是不安全的,我正试图摆脱它。
The ways React advices to refactor componentWillReceiveProps 基本上要么使用static getDerivedStateFromProps 要么使用componentDidUpdate
可悲的是,componentDidUpdate 永远不会被调用,因为shouldComponentUpdate 返回 false(我认为这很好?)而且我无法在静态方法 getDerivedStateFromProps 中访问 this.iFrame 引用。
如何重构这段代码?
【问题讨论】:
标签: javascript reactjs getderivedstatefromprops