Reactjs 在React应用程序中使用useContext替换道具
在父React组件中创建状态对象并使用useContext在嵌套组件之间上下传递数据是否有任何缺点?这会不会消除对道具的需求?似乎是一种更简单、更符合逻辑的数据组织方式。此方法是否存在任何性能或其他问题 有几点需要事先考虑:Reactjs 在React应用程序中使用useContext替换道具,reactjs,react-hooks,react-props,react-state-management,Reactjs,React Hooks,React Props,React State Management,在父React组件中创建状态对象并使用useContext在嵌套组件之间上下传递数据是否有任何缺点?这会不会消除对道具的需求?似乎是一种更简单、更符合逻辑的数据组织方式。此方法是否存在任何性能或其他问题 有几点需要事先考虑: 你不能把数据传给别人 在嵌套组件之间传递道具将导致反模式- “道具钻探”的解决方案是ContextAPI 但是,使用“仅上下文”(正如您所建议的)也可能导致反模式(“上下文地狱”?), 对于每个数据传递,您将创建一个上下文,并呈现一个提供者 此外,我看到这种方法的主要问题是
Context
API上下文
,并呈现一个提供者
此外,我看到这种方法的主要问题是,使用上下文的每个组件都会在提供者值更改时呈现,尽管它们可能不使用上下文的值
注意组件的渲染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(0, p => p + 1);
return (
<Context.Provider value={value}>
<Child id={1} />
<Memoized id={2} />
<UsingContext id={3} />
<MemoizedUsingContext id={4} />
<button onClick={render}>Render</button>
</Context.Provider>
);
};
const Context=React.createContext();
常量Child=({id})=>{
log(`rendered`,id);
返回id为{id}的子级;
};
const UsingContext=({id})=>{
使用上下文(Context);
log(`rendered using Context`,id);
使用上下文id={id}返回;
};
const MemoizedUsingContext=React.memo(使用上下文);
const Memoized=React.memo(子级);
常量应用=()=>{
const[value,render]=useReducer(0,p=>p+1);
返回(
伦德尔
);
};
谢谢您的示例。玩弄它,帮我把事情弄清楚。