简体   繁体   English

当捆绑到 commonJS 时,将 useContext 包装在钩子中返回 undefined

[英]Wrapping a useContext in a hook returns undefined when bundled to commonJS

Problem: Code stops working when bundled.问题:捆绑后代码停止工作。 I have the following hook the consumes a context, and a component that consumes that hook:我有以下钩子消耗一个上下文,以及一个消耗该钩子的组件:

const useAContext = () => {
  return useContext(AContext)
}
    
const SomeComponent = () => {
  const aContextProps = useAContext()
  ...
}

This works fine, no errors.这工作正常,没有错误。

After bundling (using rollup and babel), I get the following compiled code:捆绑后(使用汇总和 babel),我得到以下编译代码:

var useAContext = function useAContext() {
  return useContext(AContext);
};

var SomeComponent = function SomeComponent(_ref) {
  var _useAContex = useAContext();
  ...
};

I have an App then consumes the compiled code as a library package and gives me an error saying that _useAContex is undefined.我有一个应用程序,然后将编译后的代码作为库 package 使用,并给我一个错误,说_useAContex未定义。 The code is being bundled to cjs and so my thought is that cjs doesn't know how to handle passing a context thru a hook.代码被捆绑到 cjs 中,所以我的想法是 cjs 不知道如何处理通过钩子传递上下文。 Mainly looking for an explanation to this behavior, but a workaround would also be appreciated.主要是寻找对此行为的解释,但也将不胜感激。

Welp, this took me hours debugging, but I found a solution. Welp,这花了我几个小时调试,但我找到了解决方案。 Turns out bundling wasn't the issue.事实证明捆绑不是问题。

I was unknowingly trying to consume the context without first setting a provider that gave the context attributes:facepalm:我在不知不觉中尝试使用上下文而没有首先设置提供上下文属性的提供程序:facepalm:

If anyone else runs into this issue, make sure you have a Context.Provider somewhere above the render tree from where you consume the context.如果其他人遇到此问题,请确保您在使用上下文的渲染树上方的某个位置有一个 Context.Provider。

I see you already found a solution, but I will post my answer anyway:我看到您已经找到了解决方案,但无论如何我都会发布我的答案:

It's a common practice to throw an error if the context is undefined.如果上下文未定义,通常会抛出错误。 It helps to debug.它有助于调试。

const useAContext = () => {
  const context useContext(AContext)
  if (!context) {
    throw new Error('useAContext must be used inside AcontextProvider')
  }
  return context
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM