且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在官方示例中使用 useState 时出错

更新时间:2022-10-15 08:22:20

您必须重新启动 Web 服务器才能使用新版本的 React 重新编译.嗯.

This code came from here.

import React from 'react';
import useState from 'react'

let f = function() {

  const [count, setCount] = useState(0);

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

export default f;

Firstly, this line from that page...

import React, { useState } from 'react';

... results in useState being null, but I changed that line. Anyhow, I get the following error...

TypeError: react__WEBPACK_IMPORTED_MODULE_1___default(...) is not a function

This error goes way if I change the code to this...

const [count, setCount] = [1, () => {}]

So I figure useState is the problem - it's not a function. Perhaps my custom import is not doing the correct thing. In which case, why doesn't the official import work?

I'm using React 16.8.1. My packages file has these...

"react-dom": "16.8.1",
"react": "16.8.1",

I've delete the local node_modules folder and run npm install --force -g.

Console.log on useState gives...

You have to restart the web server to recompile with a new version of React. Doh.