react.js - shouldComponentUpdate 如何比较能动态传参的function

查看:143
本文介绍了react.js - shouldComponentUpdate 如何比较能动态传参的function的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

最近在做性能优化。基于 shouldComponentUpdate 来做比较。对于数据来说可以很容易比较(用了immutable)。

然而对于某些function来说怎么处理呢?

要求:能够动态传参v

假设有伪代码

class A extends React.Component{
    constructor(props) {
        super(props);
    }
    
    handleB(value){
        console.log(value);
    }
    
    render(){
        return <div>
            {[1,2,3].map(v => <B onCallback={this.handleB.bind(this, v)} />)}
        </div>
    }
}

class B extends React.Component {
    shouldComponentUpdate(nextProps){
        const thisProps = this.props;
        
        // ....省略
        
        if(thisProps.onCallback === nextProps.onCallback){
            return false;
        }
        return true;
    }
    render(){
        return ....省略;
    }
}

补充: 感谢大家,最终用了如下方案

class A extends React.Component{
    constructor(props) {
        super(props);
        this.handleB = ::this.bindB;
    }
    
    handleB(event){
        // 有了索引,就可以查到原数据了
        console.log(event.currentTarget.dataset.index); 
    }
    
    render(){
        return <div>
            {[1,2,3].map((v, i) => <B data-index={i} onCallback={this.handleB} />)}
        </div>
    }
}

解决方案

data- 来存参数

class Demo extends Component {
    constructor(props) {
        super(props);

        this.clickHandler = this.clickHandler.bind(this);
    }

    render() {
        const arr = [0, 1, 2];

        return (
            <div>
                {
                    arr.map(i => (
                        <button
                            key={i}
                            data-index={i}
                            onClick={this.clickHandler}
                        />
                    ))
                }
            </div>
        )
    }

    clickHandler(e) {
        const index = e.currentTarget.dataset.index;
    }
}

这篇关于react.js - shouldComponentUpdate 如何比较能动态传参的function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆