我有一个受this post启发的IFrameComponent组件。
它基本上看起来是这样的:
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引用。
如何重构这段代码?
发布于 2018-06-14 21:15:51
我认为,一种可能的方法是:
let iFrameRefs = {}
class IFrameComponent extends React.Component {
static getDerivedStateFromProps (props) {
if (iFrameRefs[props.id]) {
const html = getHTMLFromContent();
const fdoc = iFrameRefs[props.id].contentDocument;
fdoc.write(html);
}
return null
}
shouldComponentUpdate() {
return false;
}
render() {
return (<iframe sandbox="..." ref={f => iFrameRefs[this.props.id] = f} />);
}
}现在,从父组件向每个组件传递唯一的id。您还可以在IFrameComponent中管理id。
<IFrameComponent id='1' />
<IFrameComponent id='2' />https://stackoverflow.com/questions/50858081
复制相似问题