在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ react-reudx 如何阻止子組件更新 ?

react-reudx 如何阻止子組件更新 ?

我有2個(gè)組件,TestAge,他們都通過(guò)connect獲取數(shù)據(jù)。

其中AgeTest的子組件。

如果我在 Test父組件的shouldComponentUpdate return false ,

發(fā)現(xiàn)Test確實(shí)不更新,但是其子組件Age還是會(huì)更新(來(lái)自connect部分的數(shù)據(jù))。

問(wèn)題是,我如何阻止Age不更新??

import {change} from 'actions'


class Age extends PureComponent{
    constructor(props){
        super(props);
        this.add=this.add.bind(this);
    }
    add(){
        this.props.change({
            name:'haha',
            age:this.props.age+1
        });
    }
    render(){
        return(
            <div>
                {this.props.names}:{this.props.age}
                <input type="button"onClick={this.add} value="+"/>
            </div>
        )
    }
}
const AgeConnect=connect((state)=>{
    return state.iReducer;
},(dispatch)=>{
    return {
        change:(o)=>dispatch(change(o))
    }
})(Age);


class Test extends Component{
    constructor(props){
        super(props)
    }
    shouldComponentUpdate(){
        return false;
    }
    render(){
        return(
            <div>
                {this.props.name}
                <AgeConnect  names={this.props.name} />
            </div>
        )
    }
}



const TestConnect=connect((state)=>{
    return state.iReducer;
},(dispatch)=>{
    return {
        change:(o)=>dispatch(change(o))
    }
})(Test);

export default TestConnect;
回答
編輯回答
墻頭草

stateprops都會(huì)導(dǎo)致組件更新。
組件的父子關(guān)系中,父組件向子組件傳遞props有改變時(shí),子組件會(huì)更新。
connect高階函數(shù)也向組件提供props,該props改變,組件也會(huì)更新。
不建議隨便使用shouldComponentUpdate,最好解決的辦法從reduxstate著手,只要state不變,組件就不會(huì)更新。

2017年5月31日 08:04
編輯回答
任她鬧

Age里也寫(xiě)個(gè)shouldComponentUpdate return false啊

2017年5月14日 08:20
編輯回答
蔚藍(lán)色

你已經(jīng)自己說(shuō)了,阻止更新可以使用shouldComponentUpdate, 那么為什么不在Age組件中使用shouldComponentUpdate呢?

還有一點(diǎn)就是,為什么要在Age組件中進(jìn)行connect呢? 為什么不能通過(guò)Test組件傳遞過(guò)來(lái)呢,如果通過(guò)Test傳遞,那么是不是就不會(huì)發(fā)生你的情況了。

2017年1月27日 01:24
編輯回答
不二心

你說(shuō)的不更新應(yīng)該是值不走re-render,如果傳給子組件的props和子組件的state都沒(méi)變化的話,子組件也只是re-render一下,重新計(jì)算了vdom。做了dom-diff這個(gè)動(dòng)作,真實(shí)的dom并沒(méi)有更新
如果是要避免re-render,可以考慮子組件基礎(chǔ)purecomponent
https://juejin.im/entry/5934c...

2018年7月20日 23:42