首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重构UNSAFE_componentWillReceiveProps

重构UNSAFE_componentWillReceiveProps
EN

Stack Overflow用户
提问于 2018-06-14 20:54:47
回答 1查看 615关注 0票数 1

我有一个受this post启发的IFrameComponent组件。

它基本上看起来是这样的:

代码语言:javascript
复制
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引用。

如何重构这段代码?

EN

回答 1

Stack Overflow用户

发布于 2018-06-14 21:15:51

我认为,一种可能的方法是:

代码语言:javascript
复制
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。

代码语言:javascript
复制
<IFrameComponent id='1' />
<IFrameComponent id='2' />
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50858081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档