简体   繁体   中英

How do you update your project to use the latest version of javascript?

I am currently building a new personal React project and would like to take advantage of and play with some of the latest features added to javascript like optional chaining. I have tried including this script in my index.html file but that did not work. What is the secret to getting the latest stable build of javascript in your React project? *edit: Sorry I did not add enough information but I am trying to try out the optional chaining feature in Reactjs. However, when I run this even handler it errors out with this error message:

Button.js:18 Uncaught TypeError: props.onClick is not a function

This is true as I wanted to see how the optional chaining works but it is apparently not working here.

const eventHandler = (e) => {
        console.log(e.target.value);
        // other code
        // onClick is the function that is passed from the parent component
        props?.onClick(e);
    }

I'll be honest, I didn't fully understand this syntax until I looked into it. I didn't know that you could make the call itself optional and thought you could only do it for properties, not methods/functions. However, you can. You just need to adjust how you are using the optional chaining: Write it as:

possiblyUndefinedObject?.possiblyUndefinedFunction?.()

See Dealing with optional callbacks or event handlers

If you use callbacks or fetch methods from an object with a destructuring assignment, you may have non-existent values that you cannot call as functions unless you have tested their existence. Using ?. , you can avoid this extra test:

Also, be sure to do this in a browser that supports it (Firefox 68 does not work but Chrome 84 does).

 const foo = {} // What you have try { foo?.bar(); } catch (err) { console.error(err); // TypeError: foo?.bar is not a function } // With?.() but undefined bar try { foo?.bar?.(); // Doesn't get called } catch (err) { console.error(err); // No error } foo.bar = () => console.log("bar"); // With?.() defined bar try { foo?.bar?.(); // "bar" } catch (err) { console.error(err); // No error }

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