鍍金池/ 問答/HTML/ react組件數(shù)據(jù)來自componentWillReceiveProps與con

react組件數(shù)據(jù)來自componentWillReceiveProps與constructor

父組件用到了組件A和組件B,父組件內(nèi)部有個狀態(tài)cur,通過點(diǎn)擊button,改變cur,控制顯示組件A還是組件B

默認(rèn)顯示組件A,并在componentDidMount請求(代碼用了個定時器模擬請求的發(fā)出),得到數(shù)據(jù)a

組件A內(nèi)有個state為aa,依靠父組件傳來的propsa,數(shù)據(jù)在componentWillReceiveProps才能接收到,并將aa渲染至頁面

問題是只有第一次會渲染出來aa,當(dāng)點(diǎn)擊按鈕切換至B=>A,這時的組件A里面的stateaa了,原因是數(shù)據(jù)a已經(jīng)存在了,不會走componentWillReceiveProps了。

A組件、B組件只能同時存在一個,不能display:'none',A組件必須有一個state.aa

怎么優(yōu)雅的處理

線上代碼https://codepen.io/SongJuXin/...

import React from 'react'

class A extends React.Component {
    constructor(props){
        super(props)
        this.state={aa:''}
    }
    componentWillReceiveProps(nextprops){
        //需要通過porps傳來的數(shù)據(jù),修改this.state.aa
        if(nextprops){
            const data=nextprops.data
            if(data.a){
                this.setState({aa:data.a+data.a})
            }
        }
    }
    render() {
        return <div>
            <p>a組件</p>
            <p>{this.props.data.a}</p>
            <p>{this.state.aa}</p>
        </div>
    }
}
class B extends React.Component {
    render() {
        return <div>b組件</div>
    }
}
export default class Paterent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {cur: 'a',data:{}}
    }
    componentDidMount() {
        //模擬一個請求
        setTimeout(()=>{
            this.setState({data:{a:'a'}})
        },200)
    }

    handleClick = () => {
        this.setState({cur: this.state.cur == 'a' ? 'b' : 'a'})
    }

    render() {
        const {cur,data} = this.state
        return (<div>
            <button onClick={this.handleClick}>{cur}</button>
            {
                //這里用cur=='a'&&data.a?<A/>:<B/>的話,不太優(yōu)雅
                cur == 'a'
                    ?<A
                        data={data}
                     />
                    : <B/>
            }
        </div>)
    }
}
回答
編輯回答
別逞強(qiáng)

我覺得最優(yōu)雅的方式就使用router。
其實呢,三目運(yùn)算也還不錯哦。

2017年9月22日 22:35