Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

javascript - TypeError dispatcher.useState is not a function when using React Hooks

I have this component:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

function App() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

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

export default App;

as I want to try out the new React hooks proposal by installing [email protected] in my package.json, but I'm getting an error:

TypeError: dispatcher.useState is not a function

  2 | import ReactDOM from "react-dom";
  3 | 
  4 | function App() {
> 5 |   const [count, setCount] = useState(0);
    |                                     ^
  6 |   useEffect(() => {
  7 |     document.title = `You clicked ${count} times`;
  8 |   });

What did I do wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There could be many reasons, and most are due to version incompatibilites or using a ^ in package.json:

1. Ensure react and react-dom are of the same version

Ensure that you have also updated the react-dom package and it is of the same version as react. In general react and react-dom should always be the same version in package.json as the React team updates them together.

If you want to install React 16.7.0-alpha.2, check that you are not using the ^ as you will install 16.7 instead, which doesn't have hooks.

Example package.json:

{
  ...
  "dependencies": {
    "react": "16.8.4", // Make sure version is same as react-dom
    "react-dom": "16.8.4",
    ...
  }
}

2. react-test-renderer is of the same version as react and react-dom

If you are using Jest, ensure that react-test-renderer is of the same version as react and react-dom:

Example package.json:

{
  ...
  "dependencies": {
    "react": "16.8.4",
    "react-dom": "16.8.4",
    "react-test-renderer": "16.8.4",
    ...
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...