react中hooks:useContext

52 阅读1分钟

如果在多层嵌套的父子通信时都要通过props得到并解构,还会太麻烦

    function Child(){
      const {count,setcount}=props;
      return <>
      <h1>{count}</h1>
      <button onClick={()=>setcount(count+1)}>+</button>
      <button onClick={()=>setcount(count-1)}>-</button>
      </>
    }
    function parent(props){
      const {count,setcount}=props;
      return <>
      <Child count={count}setcount={setcount}/>
      </>
    }
    function Myapp()
    {
      const {count,setcount}=setState(0);
      return <>
      <parent count={count} setcount={setcount}/>
      </>}

所以引入useContext,想要用context需要先创建环境对象createContext const Mycontext = CreateContext(); 2.配置环境对象并传值 用context.Provider包裹

      <Mycontext.Provider value={{count,setcount}}>
        <h1>根组件<h1/>
      <parent count={count} setcount={setcount}/>
      <Mycontext>

这样里面的value这个对象里的数据和操作数据的方法就可以直接传递给子组件和子组件的子组件。 子组件拿值 在子组件中用useContext拿到创建的全局环境对象值匹配的值,减少props的接收 const {count,setcount}=useContext(Mycontext);