React Context API not working from custom NPM component library

后端 未结 3 924
清酒与你
清酒与你 2021-02-19 20:24

I\'ve built a ReactJS component library that I use for multiple projects installed via an NPM package using a sim link. I want to use the context API to pass data from a parent

相关标签:
3条回答
  • 2021-02-19 20:45

    should your code of consumer be

          <React.Fragment>
            <MyContext.Consumer>
              {value => /* render something based on the context value */}
            </MyContext.Consumer>
          </React.Fragment>
    

    as stated from the official react doc : https://zh-hant.reactjs.org/docs/context.html

    when you define

    you can use it like

    0 讨论(0)
  • 2021-02-19 20:46

    Maybe you are making multiple instances of the component providing the context. Let's say you have a component Sound, which starts by:

        const { Provider, Consumer } = React.createContext();
    

    If you import this library from your main project, the context will be created at the global space. You then use it to render your document tree. But in another component you also imported this library, which had to be resolved during webpack transpilation. It thus has its own copy of the above lines and a context object created in its own space. The problem occurs when you try to use the Consumer, because the Provider was only made by the main project for the first context object, and the second context's provider instance was never instantiated, thus returns undefined.

    A solution to the problem is to enforce a single context object, which you can achieve by telling the second component's webpack that the provider-owning library is an external, so when webpack reaches e.g. the "import sound" line, it will not go further and will assume this dependency is resolved at runtime. When runtime comes, it will take it from the same place where the main project is taking it. To do this in webpack, e.g. for above "sound" library, add this to your other component (not main project):

    {
       ...
       externals: {
          ...
          'sound': 'sound'
       }
       ...
    }
    

    Also in your component package.json:

    {
       ...
       peerDependencies: {
         "sound": "^1.2.3"
       }
    }
    
    0 讨论(0)
  • 2021-02-19 20:53

    Apart from Darko's answer, esm and cjs export is also a possible reason for context to fail in a package. If you use the hook in esm and the provider in cjs, you will not get the value for that context.

    0 讨论(0)
提交回复
热议问题