父组件用到了组件A
和组件B
,父组件内部有个状态cur
,通过点击button
,改变cur
,控制显示组件A
还是组件B
默认显示组件A
,并在componentDidMount
请求(代码用了个定时器模拟请求的发出),得到数据a
组件A
内有个state为aa
,依靠父组件传来的propsa
,数据在componentWillReceiveProps
才能接收到,并将aa
渲染至页面
问题是只有第一次会渲染出来aa
,当点击按钮切换至B=>A,这时的组件A
里面的stateaa
了,原因是数据a
已经存在了,不会走componentWillReceiveProps
了。
A组件、B组件只能同时存在一个,不能display:'none',A组件必须有一个state.aa
怎么优雅的处理
import React from 'react'
class A extends React.Component {
constructor(props){
super(props)
this.state={aa:''}
}
componentWillReceiveProps(nextprops){
//需要通过porps传来的数据,修改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/>的话,不太优雅
cur == 'a'
?<A
data={data}
/>
: <B/>
}
</div>)
}
}
我觉得最优雅的方式就使用
router
。其实呢,三目运算也还不错哦。