React很難,尤爲對於新手。程序員
緣由是設置和邏輯比較隨意,並且這麼多年出現了不少Pattern,新手通常不會研究什麼pattern,能寫就行。可是高手通常很注重pattern,好比比HOC還要聰明的,還要高級的,還要很差理解的是有高手發明的: Render Callbackredux
一:提煉下Render Callback的模式patternbash
Step1:構造Stateless無狀態Functional COMP(由於他不用關心State,純粹表現presentational component)。less
Let PureComponent=(props)=>{
return (
<StateComponent ownProps="" passProps={props}>
{ //parse
(passState)=>{
return (//render things...
{passState.loading && <h2>Laoding..</h2>}
.......
)
}
}
</StateComponent>
)
}
複製代碼
即:能夠簡寫shorthand(注意())函數
Let PureComponent=(props)=> (
<StateComponent ownProps="" passProps={props}>
{ //parse
(passedState,passedMethod)=> (//render things...
<div>
{passedState.loading && <h2>Laoding..</h2>}
<button onClick={passedMethod.toggle}/>
.......
</div>
)
}
</StateComponent>
)
複製代碼
Step2:構造Statefull Component, 即Class Component(由於必需State)。ui
Class StateComponet extends Component{
state:{
show:false,
};
toggle=()=>{
this.setState(
prevState=>({
show:!prevState.show
})
)
};
render(){
return(
this.props.children(
this.state, {
toggle:this.toggle
....
}
}
)
)
};
複製代碼
注意:爲確保能更新,這裏用了setState updater: (prevState, prevProps) => stateChangethis
另外注意:參數順序相反componentDidUpdate(prevProps, prevState, snapshot)spa
二:跟Redux模式和邏輯對比下code
Redux的思路是:component
Class ReduxComponet extends Component{
state:{
//State僅僅是本地localstate,
//其餘State在Redux
};
toggle=()=>{
this.props.passedActionFromRedux(...);
//操做也在redux
};
render(){
return(
<h2>{this.passedReduxState.show}..</h2>}
<button onClick={this.toggle}/>
)
};
...MapStateToProps..
...MapReduxAction..
複製代碼
怎麼樣,理解了嗎?!