【问题标题】:React hooks not working when imported from local library从本地库导入时,React 钩子不起作用
【发布时间】:2019-10-17 13:58:24
【问题描述】:

我正在使用 React 导入一个带有 useState 钩子的函数,这似乎破坏了它。我有一个用钩子做出反应的版本:

npm ls react => react@16.10.2
npm ls react-dom => react-dom@16.10.2

我可以很好地使用组件。当我包含一个钩子时,我会看到“无效的钩子调用”屏幕。

在我的图书馆项目中,我有:

/**
 * @class ExampleComponent
 */

import * as React from 'react'

import styles from './styles.css'

export default function ThingyDefault() {
  return <p>hi</p>
}

export type Props = { text: string }

export class ExampleComponent extends React.Component<Props> {
  render() {
    const {
      text
    } = this.props

    return (
      <div className={styles.test}>
        Example Component: {text}
      </div>
    )
  }
}

////////////////// THIS DOESN'T SEEM TO WORK //////////////////
export function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

在我使用该库的项目中:

import React from 'react';
import './App.css';
import ThingyDefault, {ExampleComponent, Example} from 'thingy';

const App: React.FC = () => {
  return (
    <div>
    <ThingyDefault />
    <ExampleComponent text='hello' />

    {/* commenting this component out makes it work */}
    <Example />
    </div>
  );
}

export default App;

我在这里做错了什么?

【问题讨论】:

  • 您的代码中似乎有多个版本的 react

标签: reactjs typescript react-hooks


【解决方案1】:

您没有遵守Rules of Hooks,特别是在您的情况下,从标准 javascript 函数调用钩子。

仅从 React 函数调用 Hooks 不要从常规 JavaScript 函数中调用 Hooks。相反,您可以:

✅ 从 React 函数组件调用 Hooks。 ✅ 从自定义 Hooks 调用 Hooks(我们将在下一页了解它们)。 通过遵循此规则,您可以确保组件中的所有有状态逻辑在其源代码中都清晰可见。

【讨论】:

  • 我从官方文档中粘贴过来的:reactjs.org/docs/hooks-state.html
  • 看起来您正在使用打字稿,所以我对语法有点不确定,但在我看来 export function Example() 存在问题,它没有被视为反应功能组件,而只是一个普通的旧 javascript 函数。不过只是猜测。
  • 如果您暂时将问题函数移动到与您的消费组件相同的文件中,那么它可以工作吗?这会告诉我们它是否是一个导入问题。
  • 库是否以某种特殊方式使用钩子导出函数?
  • 知道了。我使用了一个 repo 来生成我的组件库:medium.com/@xfor/… 并通过使用 stackoverflow.com/questions/16073603/… 将所有依赖项更新到最新版本来修复它创建的问题,我终于让它与带有钩子的组件一起工作。谢谢你的帮助。我会将此标记为答案,以便为所提供的帮助打分。
【解决方案2】:

由于这似乎是一个导入/导出问题,请尝试将您的导出更改为:

const Example = () => {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
export { Example };

【讨论】:

  • 试过但没有成功。
【解决方案3】:

你没有做错什么。 它应该按预期工作。检查example Stackblitz here,使用与您拥有的相同版本的 React。

我可能会重新检查应用程序是否有任何重复的依赖项弄乱了钩子的功能。尤其是无法确定你的function Example(),确实是一个功能组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多