React Context API not working from custom NPM component library

后端 未结 3 931
清酒与你
清酒与你 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: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"
       }
    }
    

提交回复
热议问题