react組件props和state屬性以及更新優(yōu)化

  • state指的的是組件中的狀態(tài),這個是不能直接供給別人使用的,需要props

  • props是指父傳遞給子組件的

  • 父組件更新state,導(dǎo)致props也更新了,如果子組件使用的是state,此時(shí)子組件render鉤子函數(shù)會觸發(fā),但是數(shù)據(jù)不會變,因?yàn)樽咏M件的state不會自動更新

    class Persion extends React.Component{
        constructor(props){
            super(props)
            this.state ={
                lists : ['a'],
                bool:1
            }
        }
        onhandle=()=>{
            this.setState({lists:[...this.state.lists,Math.floor(Math.random()*10)]})
        }
        onBool=()=>{
            this.setState({bool:Math.floor(Math.random()*10)})
        }
        render(){
            return(
                <div>
                    <Clid  lists={this.state.lists}></Clid>
                    <button onClick={this.onhandle}>addList</button>
                    <button onClick={this.onBool}>bool</button>
    
                </div>
                
            )
        }
    }
    class Clid extends React.Component{
        constructor(props){
            super(props)
            this.state ={
                lists : this.props.lists
            }
        }
        render(){
            debugger;
            return (
                <div>
                <ul>
                    {
                        this.state.lists.map((li,index)=>{
                        return <li key={index+li}>{li}</li>
                        })
                    }
                </ul>
            </div>
            )
        }
    }
    
  • 點(diǎn)擊addList按鈕,父組件狀態(tài)更新,子組件會重新渲染(但不會重新創(chuàng)建),此時(shí)子組件用數(shù)據(jù)是this.state.lists,由于是重新渲染,而不是重新構(gòu)建,所有不走初始化,因此子組件的state沒有變
    解決方案:

  • 將this.state.lists改為this.props.lists,子組件渲染的數(shù)據(jù)直接從props中獲取,一般這種寫法適合數(shù)據(jù)只依賴于父組件props的

  • 使用 getDerivedStateFromProps鉤子函樹,接收最新的props和當(dāng)前的state。根據(jù)判斷,更新state

  • 性能優(yōu)化props更新時(shí)才出發(fā)子組件的渲染

    • shouldComponentUpdate,當(dāng)父組件的state更新或者子組件的props更新,該鉤子函數(shù)會被調(diào)用,判斷是否需要重新渲染。
    • React.memo用于創(chuàng)建函數(shù)組件時(shí)使用,被其包裹的組件,只有props更新才會重新創(chuàng)建
    • userComponent創(chuàng)建的組件只有當(dāng)props更新時(shí)才會重新渲染
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容