简体   繁体   English

自定义钩子工厂可以在项目中工作,但不能作为npm依赖项

[英]Custom hook factory works in project but not as npm dependency

I was attempting to factor this custom-hook-creating-factory-function out of an application into a library. 我试图将这个自定义钩子创建工厂功能从应用程序分解到库中。 I moved it into it's own project, made sure tests still passed, etc. Then to test it before I committed changes to the original project I npm install ../path/to/extracted/library and changed the import in the original project. 我将其移至其自己的项目中,确保测试仍然通过, npm install ../path/to/extracted/library 。然后在对原始项目进行更改之前进行测试,我将npm install ../path/to/extracted/library并更改了原始项目中的导入。 Only now I get an invalid hook call error. 直到现在,我收到一个无效的挂接调用错误。 Here's the built file from the library project: 这是库项目中的构建文件:

import React, { createContext, useContext, useReducer } from 'react';

export default () => {
  const StateContext = createContext([{}, (() => { })]);
  const CtxProvider = ({ reducer, children, initialState = {}, }) => {
    const [state, dispatch] = useReducer(reducer, initialState);
    return React.createElement(StateContext.Provider, { value: [state, dispatch] }, children);
  };

  return [
    () => useContext(StateContext),
    CtxProvider,
  ];
};

It's a factory that returns a tuple with a custom hook that yields a context value and the reducer dispatch function, and a provider component that takes the reducer and initial state as props and provides the context. 这是一家工厂,该工厂返回一个元组,一个带有自定义钩子的元组,该钩子产生一个上下文值和reducer调度函数,以及一个提供者组件,该组件将reducer和初始状态作为props并提供上下文。 When I import it via npm like so 当我像这样通过npm导入时

import customHookFactory from 'extracted-libaray-name';

I get the invalid hook call error. 我收到无效的挂接调用错误。

When I import the exact same code copy-pasted into a local file like so: 当我将完全相同的代码复制粘贴到本地文件中时,如下所示:

import customHookFactory from '../utils/local-file';

I don't get the error. 我没有得到错误。 Huh? ?? I'm using react-scripts 'start' from CRA to develop, and I'm assuming it's doing something to my local project files it's not doing to node_modules or vice-versa, but I don't know what. 我正在使用从CRA开始的react-scripts“开始”进行开发,并且我假设它正在对本地项目文件做某事,而对node_modules却没有做,反之亦然,但是我不知道是什么。

Okay, figured it out after much futzing and reading the suggestions from the React error . 好吧,经过大量的讨论并从React错误中阅读了建议之后,才知道了这一点。

I had listed React and react-dom as dependencies of my extracted library rather than a peer dependency, so they were different copies of react. 我已将React和react-dom列为提取的库的依赖项,而不是对等依赖项,因此它们是react的不同副本。 Changing the extracted library to use React as a peerDependency and re-installing fixed it. 更改提取的库以将React用作peerDependency并重新安装修复它。

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

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