【发布时间】:2019-05-01 04:56:31
【问题描述】:
所以我想避免 props 的深度嵌套,我开始使用 React 上下文来做到这一点,但后来我突然想到“为什么不直接导出对象?”
例如,不要写:
const handleClick: = event => {
event.preventDefault();
doSomething();
};
const calcPrice = (quantity) = {
return quantity * 100
};
export const ComponentContext = createContext({});
export const ParentComponent = () => {
return (
<ComponentContext.Provider value={{ handleClick, calcPrice }}>
<ChildComponent quantity={12} />
</ComponentContext.Provider>
}
并将其导入为:
export const ChildComponent = (quantity) = {
const { handleClick, calcPrice } = useContext(ComponentContext);
const totalPrice = calcPrice(quantity);
return <button onClick={handleClick}>Total is ${totalPrice}</button>
}
我可以简单地写成:
const handleClick: = event => {
event.preventDefault();
doSomething();
};
const calcPrice = (quantity) = {
return quantity * 100
};
export const componentProps = { handleClick, calcPrice };
export const ParentComponent = () => {
return <ChildComponent quantity={12} />
}
并将其导入为:
const { handleSignUpClick, calcPrice } = componentProps;
export const ChildComponent = (quantity) = {
const totalPrice = calcPrice(quantity);
return <button onClick={handleClick}>Total is ${totalPrice}</button>
}
使用上下文而不是函数的优势是什么?
【问题讨论】:
-
doSomething()inhandleClick需要做什么?这似乎不太可能对您的应用程序状态没有某种依赖性。如果handleClick对 state 或 props 没有任何依赖,那么就没有理由使用 context。 -
它涉及更改状态(将 dialogOpen 状态从 false 更改为 true,以便打开对话框表单)。我现在实际上正在使用自定义反应挂钩来执行此操作,而不是上下文或对象,因为
handleClick()需要包含一个挂钩本身。
标签: reactjs react-hooks