上集 講到上手了Context API來解決props drilling問題,下文就講解如何利用高階組件(HOC)復(fù)用Context,使其能多個(gè)地方使用這好玩的特性
// contextHOC.js
// 用屬性代理的方法造高階組件
const Provider = ({Provider},store={}) => Wrappedcomponent => {
return class extends Component {
state = store
// 頂層修改state方法
updateState = state => setState(state)
render() {
return (
<Provider
value={{
...state,
updateState: this.updateState, // 消費(fèi)者調(diào)用props.context.updateState就能修改頂層state
}}
>
<Wrappedcomponent {...this.props} />
</Provider>
)
}
}
}
const Consumer = ({Consumer}) => Wrappedcomponent => {
return class extends Component {
render() {
return (
<Consumer>
{
// context注入props里
data => <Wrappedcomponent context={{...data}} {...this.props} />
}
</Consumer>
)
}
}
}
// 導(dǎo)出
export defalut {
Provider,
Consumer,
}
// index.js(只展示核心代碼,從上到下順序)
// 干凈的組件A,B1,B2
class A extends Component {
render() {
return (
<div style={{ background: "gray" }}>
<p>父組件</p>
<B1 />
<B2 />
</div>
);
}
}
// 子組件1 ConsumerC1由高階組件和組件C1生成的,需往下看
class B1 extends Component {
render() {
return (
<div style={{ background: "yellow", width: "400px" }}>
<p>子組件1</p>
<ConsumerC1 />
</div>
);
}
}
// 子組件2 ConsumerC2由高階組件和組件C2生成的,需往下看
class B2 extends Component {
render() {
return (
<div style={{ background: "yellow", width: "400px" }}>
<p>子組件2</p>
<ConsumerC2 />
</div>
);
}
}
// 孫組件1
class C1 extends Component {
handleClick = () => {
const { updateState, num } = this.props.context;
updateState({
num: num + 1
});
};
render() {
console.log("c1 render");
return (
<div style={{ background: "white", width: "200px" }}>
<p>孫組件1</p>
<button onClick={this.handleClick}>點(diǎn)我</button>
</div>
);
}
}
// 孫組件2
class C2 extends Component {
render() {
const { num } = this.props.context;
console.log("c2 render");
return (
<div style={{ background: "pink", width: "200px" }}>
<p>孫組件2</p>
<p>num:{num}</p>
</div>
);
}
}
const ProviderA = ContextHOC.Provider(AppContext, { num: 0 })(A);
const ConsumerC1 = ContextHOC.Consumer(AppContext)(C1);
const ConsumerC2 = ContextHOC.Consumer(AppContext)(C2);
// 這里用函數(shù)的方法生成高階組件,其實(shí)使用時(shí)可以利用es7的decorator修飾器功能,因?yàn)樵诰€代碼編輯的網(wǎng)站不知怎么配置修飾器語法
// @ContextHOC.Provider(AppContext,{num:0})
// class A extends Component {}
//...
// @ContextHOC.Consumer(AppContext)
// class C1 extends Component {}
// ...
// 語義性更好的@connect()寫法
// ...
// ...
然而發(fā)現(xiàn)點(diǎn)擊按鈕時(shí),兩個(gè)消費(fèi)者C1,C2同時(shí)re-render,理想情況是C1不觸發(fā)重新渲染,這是什么原因造成呢?

控制臺發(fā)現(xiàn)多余的re-render