3

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

4

1 回答 1

3

有一些注意事项应该事先考虑:

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

  2. 在嵌套组件之间传递 props 会导致一种反模式—— “props钻孔”

  3. “道具钻孔”的解决方案是ContextAPI

但是,在使用“仅上下文”(如您所建议的那样)也可能导致反模式(“上下文地狱”?),对于每个数据传递,您将创建 aContext并渲染 a 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>
  );
};

编辑 blue-meadow-0pxzr

于 2020-03-06T17:29:41.173 回答