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

前端 未结 7 721
失恋的感觉
失恋的感觉 2020-12-06 09:04

I have this component:

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

function App() {
  const [count, setCount]          


        
相关标签:
7条回答
  • 2020-12-06 09:21

    I just updated to the latest version of react and react DOM, it works for me. Check React versions here

    0 讨论(0)
  • 2020-12-06 09:29

    Fixed mine by calling React.useState(0).

    If a react version is new enough, it just has to use React.useState.

    0 讨论(0)
  • 2020-12-06 09:32

    You may get same error when using jest. So to fix the error I had to update react-test-renderer to have the same version as react and react-dom

    yarn add -D react-test-renderer@next
    

    Or

    npm i react-test-renderer@next
    

    All react, react-dom and react-test-renderer should contain same version

    "react": "^16.7.0-alpha.0",
    "react-dom": "^16.7.0-alpha.0",
    "react-test-renderer": "^16.7.0-alpha.0"
    
    0 讨论(0)
  • 2020-12-06 09:33

    Make sure that you have imported useState correctly.

    import React, {useState} from 'react';

    0 讨论(0)
  • 2020-12-06 09:37

    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",
        ...
      }
    }
    
    0 讨论(0)
  • 2020-12-06 09:40

    Use React and {useState}:

    import React,{useState} from 'react';
    
    const Renu = () => {
        const[heart,heartSet]= useState('renu'); 
        return(
            <h1>vikas love {heart}</h1>
        )
    }
    
    export default Renu;
    
    0 讨论(0)
提交回复
热议问题