React Hooks 之 useContext

51 阅读1分钟

什么是context

React自带API context可解决多层级组件的数据传递问题

React是单向数据流,如果A>B>C三个组件逐层嵌套,在没有状态管理的情况下,只能通过props一层一层的进行传递,当组件间的调用过多的时候,维护会变得十分复杂。context可解决这一问题。

context的使用

  1. 使用createContext建立一个context,并导出
  2. 传递数据组件里使用Provide包裹着子组件,使用value传递数据
  3. 接受数据的组件使用Consumer包裹函数,使用函数接收数据。
// 组件A
import React from "react";
import B from "./B";

export const barContext = React.createContext("");
export default function App() {
  return (
    <barContext.Provider value={"bar"}>
      组件A
      <B />
    </barContext.Provider>
  );
}

// 组件B
import C from "./C";

export default function B() {
  return (
    <>
      组件B,
      <C />
    </>
  );
}

// 组件C
import React from "react";
import { barContext } from "./A";

export default function C() {
  return (
    <barContext.Consumer>
      {(bar) => <span>我叫{bar}</span>}
    </barContext.Consumer>
  );
}

useContext的使用

可替换掉Consumer消费数据部分。

//组件 C
import React, { useContext } from "react";
import { barContext } from "./A";

export default function C() {
  const bar = useContext(barContext)
  return (
    <div>
      <span>我叫{bar}</span>
    </div>
  );
}

优势是使用简便,在多context存在场景下,调用清晰。

两种消费方式对比

//组件 C
import React from "react";
import { barContext, fooContext } from "./A";

export default function C() {
  return (
    <barContext.Consumer>
      {(bar) => (
        <>
          <span>{bar}</span>
          <fooContext.Consumer>
            {(foo) => <span>{foo}</span>}
          </fooContext.Consumer>
        </>
      )}
    </barContext.Consumer>
  );
}

//组件 C
import React, { useContext } from "react"
import { barContext, fooContext } from "./A"

export default function C() {
  const bar = useContext(barContext)
  const foo = useContext(fooContext)
  
  return (
    <span>
      {bar}
      {foo}
    </span>
  )
}