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也不在话下。

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