【问题标题】:Uncaught TypeError: Object (...) is not a functionUncaught TypeError: Object (...) is not a function
【发布时间】:2019-12-03 12:14:06
【问题描述】:

我对 Preact 很陌生,当我想在 Preact 中使用钩子时,我收到一个错误:

Uncaught TypeError: Object(...) is not a function

我不知道该怎么做,网上有一些关于 Preact 的文章

这是我的代码

import './style';
import { useState } from 'preact';

function App() {
  const [value, setValue] = useState(0);
  const increment = useCallback(() => setValue(value + 1), [value]);

  return (
    <div>
      Counter: {value}
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default App

【问题讨论】:

  • 是否有任何答案解决了您的问题?
  • 不是它自己修复的

标签: javascript preact


【解决方案1】:

您输入错误。应该是:

import { useState } from 'preact/hooks';

在此处查看文档:https://preactjs.com/guide/v10/hooks/#usestate

【讨论】:

    【解决方案2】:
    import './style';
    import { useState } from 'preact';
    
    const App = props => {
      const [value, setValue] = useState(0);
      const increment = useCallback(() => setValue(value + 1), [value]);
    
      return (
        <div>
          Counter: {value}
          <button onClick={increment}>Increment</button>
        </div>
      );
    };
    
    export default App;
    

    【讨论】:

    • 我想你忘了导入 useCallback 钩子。它应该是 import { useState,useCallback } from 'preact/hooks';