在出現useContext
之前,使用context
的方式主要是兩種,第一種需要使用Consumer
:
class Component2 extends Component{
render(){
return (
<CountContext.Consumer>
{
count => <div>{count}</div>
}
</CountContext.Consumer>
);
}
}
這種方法非常常見,而且是函數組件在hooks出現之前唯一的使用context
的方法。
上面那樣的寫法顯然不太簡便,那麼對於類組件來說,可以使用ContextType
來簡化寫法:
class Component1 extends Component{
static contextType = CountContext;
render(){
const count = this.context;
return (
<div>{count}</div>
);
}
}
對照最上面的代碼,的確簡潔了一些。
但是以上兩種方式都有一些問題,對於直接使用Consumer
的方式來說就是代碼不夠簡潔。而對於ContextType
的方式來說,一個類組件只能設置一個ContextType
,而且函數組件沒法使用。
那麼useContext
這個hooks函數的出現就解決了以上問題:
function Component3(props){
const count = useContext(CountContext);
return (
<div>{count}</div>
);
}
可以看到代碼比之前的要更加簡潔,也不需要寫Consumer
。而且useContext
可以使用多次,也就是說同時簡潔地使用多個context
也不在話下。