React--useContext

在出現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也不在話下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章