React 16.7 Hooks:`react.useState`不是函数

时间:2018-11-13 14:08:07

标签: reactjs react-hooks

我正在尝试使用带有react 16.7的钩子的功能组件,但是有一个错误:

enter image description here

src / components / Footer / index.js

function Footer() {
  const [selectedTab, setSelectedTab] = useState('redTab');
  const [hidden, setHidden] = useState(false);
  const [fullScreen, setFullScreen] = useState(false);
 //...
}

package.json

enter image description here

我该怎么办?

3 个答案:

答案 0 :(得分:10)

确保也将react-dom升级到16.7.0-alpha.0

package.json

{
  "dependencies": {
    "react": "16.7.0-alpha.0",
    "react-dom" "16.7.0-alpha.0",
    ...
  },
  ...
}

也可能是您仅在package.json中修改了版本,而未安装新版本。 You can remove node_modules and install again

npm ci

示例

const { useState } = React;

function Footer() {
  const [selectedTab, setSelectedTab] = useState('redTab');
  const [hidden, setHidden] = useState(false);
  const [fullScreen, setFullScreen] = useState(false);
  
  return (
    <div>
      <button onClick={() => setSelectedTab('blueTab')}>{selectedTab}</button>
      <button onClick={() => setHidden(isHidden => !isHidden)}>
        {hidden ? 'hidden' : 'visible'}
      </button>
      <button onClick={() => setFullScreen(isFullScreen => !isFullScreen)}>
        {fullScreen ? 'fullscreen' : 'windowed'}
      </button>
    </div>
  );
}

ReactDOM.render(
  <Footer />,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="root"></div>

答案 1 :(得分:2)

package.json中的React和React-dom版本不同

因此,要解决此问题,您需要将react-dom升级到与react相同的版本

运行以下命令。这将安装react-dom版本16.7.0-alpha.0

 npm i -s react-dom@16.7.0-alpha.0

安装react-dom后,重新捆绑项目。

答案 2 :(得分:0)

我已经see in this package.json安装了react和react-dom alpha。

在同一项目中使用以下代码将可以正常工作:

import React, { useRef, useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const [icount, setICount] = useState(0);
  const {current: increment} = useRef(1 + Math.floor(Math.random() * 5));
  return (
    <div>
      Count {count}<br />
      Increment {increment}<br />
      <button onClick={() => {
        setCount(count + 1);
        setICount(icount + increment);
      }} clicks={count}>
        Current {icount}
      </button>
    </div>
  );
}

export default Counter;

可以通过以下基本应用测试/使用该导出:

import React from 'react';
import ReactDOM from 'react-dom';
import Counter from './Counter';

ReactDOM.render(<Counter />, document.body);

我希望这个例子可以澄清/解决您的问题。

最好的问候