使用React Hooks时,TypeError dispatcher.useState不是函数 [英] TypeError dispatcher.useState is not a function when using React Hooks

查看:174
本文介绍了使用React Hooks时,TypeError dispatcher.useState不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个组件:

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;

因为我想尝试新的中安装 react@16.8.1 ,docs / hooks-intro.htmlrel =nofollow noreferrer> React hooks 提案package.json ,但是我收到一个错误:

as I want to try out the new React hooks proposal by installing react@16.8.1 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 |   });

我做错了什么?

推荐答案

可能有很多原因,大多数是由于版本不兼容或在 package.json中使用 ^

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


  1. 确保您还更新了 react-dom 包,相同的版本 。通常 react react-dom 应该始终是 package.json中的相同版本当React团队一起更新它们。

  1. 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.

如果你想安装React 16.7.0-alpha.2 ,检查您是否使用 ^ ,因为您将安装16.7而不是挂钩。

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.

示例 package.json

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








  1. 如果您使用的是Jest,请确保 react-test-renderer 版本与反应 react-dom

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

示例 package.json

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

这篇关于使用React Hooks时,TypeError dispatcher.useState不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆