在 React 应用程序中用 useContext 替换 props

Replace props with useContext in React Application

在父 React 组件中创建状态对象并使用 useContext 在嵌套组件之间上下传递数据是否有任何缺点?这会消除对道具的需求吗?似乎是一种更简单、更合乎逻辑的数据组织方式。这种方法有任何性能或其他问题吗?

有几点需要事先考虑:

  1. 您不能将数据向上传递为 Data Flows Down

  2. 在嵌套组件之间传递 props 会导致反模式 - "props drilling"

  3. “道具钻”的解决办法是ContextAPI

但是,使用“仅上下文”(如您所建议的)也可能导致反模式(“上下文地狱”?), 至于 每个 数据传递,您将创建一个 Context 并渲染一个 Provider.

此外,我发现这种方法的主要问题是 每个使用上下文的组件都会在提供程序值更改时呈现 ,尽管它们可能不使用上下文的值。

注意组件的渲染 3,4:

const Context = React.createContext();

const Child = ({ id }) => {
  console.log(`rendered`, id);
  return <div>Child with id = {id}</div>;
};

const UsingContext = ({ id }) => {
  useContext(Context);
  console.log(`rendered using Context`, id);
  return <div>Using Context id = {id}</div>;
};

const MemoizedUsingContext = React.memo(UsingContext);
const Memoized = React.memo(Child);

const App = () => {
  const [value, render] = useReducer(p => p + 1, 0);

  return (
    <Context.Provider value={value}>
      <Child id={1} />
      <Memoized id={2} />
      <UsingContext id={3} />
      <MemoizedUsingContext id={4} />
      <button onClick={render}>Render</button>
    </Context.Provider>
  );
};