简体   繁体   中英

Failed to compile: <function name> is not defined no-undef

I have a simple functional component in reactJS with arrow function defined inside of it. For some reason it throws a "not defined" error through the function exits. It works in my other repository not sure why it started to throw this error.

My code:

Template.js

// Dependencies
import React, { useState } from 'react';


function Login(props) { 


    handleChange = () => {
        console.log('Hello');
    }


    return (
        <div>
            <p> Hello </p>
        </div>
    );
};


export default Login;

Error:

./src/screens/Template.js Line 8: 'handleChange' is not defined no-undef

Search for the keywords to learn more about each error. This error occurred during the build time and cannot be dismissed.

You have to write "const" at your arrow function's beginning. Because it's not in a class component.

const handleChange = () => { console.log('Hello'); }

or you can use just with;

function handleChange() { console.log('Hello'); }

handleChange is a variable you defined, so please try to add const or let before handleChange to see if the error dismissed.

// Dependencies
import React, { useState } from 'react';


function Login(props) { 


    const handleChange = () => {
        console.log('Hello');
    }


    return (
        <div>
            <p> Hello </p>
        </div>
    );
};


export default Login;

use const as to define a function. But I suggest you to write like this:

// Dependencies
import React, { useState } from 'react';

// Outside of your component, for performance 
const handleChange = () => {
    console.log('Hello');
}

function Login(props) { 
  return (
    <div>
        <p> Hello </p>
    </div>
  );
};


export default Login;

The reason for the error is that the variable handleChange has not been declared. In Javascript you can declare it in one of these ways:

  • var handleChange = () => {...}
  • const handleChange = () => {...}
  • let handleChange = () => {...}
  • function handleChange() {...}

But you cannot simply start using handleChange without declaring it as a variable. The language parser doesn't know what it is and gives the error you see.

If it was working in similar code, then the variable must have been declared earlier in the program, but I'd need to see the other implementation to know for sure. Perhaps it was like this:

var handleChange;

/* some other code here */
handleChange = () => { console.log("I work because I was declared earlier"); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM