简体   繁体   English

您如何更新您的项目以使用最新版本的 javascript?

[英]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.我目前正在构建一个新的个人 React 项目,并希望利用并使用 javascript 中添加的一些最新功能,例如可选链。 I have tried including this script in my index.html file but that did not work.我曾尝试在我的 index.html 文件中包含此脚本,但这不起作用。 What is the secret to getting the latest stable build of javascript in your React project?在您的 React 项目中获得 javascript 的最新稳定版本的秘诀是什么? *edit: Sorry I did not add enough information but I am trying to try out the optional chaining feature in Reactjs. *编辑:抱歉,我没有添加足够的信息,但我正在尝试 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 Button.js:18 Uncaught TypeError: props.onClick 不是 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.如果您使用带有解构赋值的 object 的回调或获取方法,您可能有不存在的值,除非您测试了它们的存在,否则您无法将其作为函数调用。 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).此外,请务必在支持它的浏览器中执行此操作(Firefox 68 不起作用,但 Chrome 84 可以)。

 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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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