【问题标题】:How to avoid eslint rule no-unneeded-ternary violation: 'Unnecessary use of conditional expression for default assignment'如何避免 eslint 规则 no-unneeded-ternary 违规:“不必要地使用条件表达式进行默认赋值”
【发布时间】:2017-08-25 02:10:46
【问题描述】:

这是我的代码

class Message extends Component {

  render() {
    const { message, timeToRedirect } = this.props;
    const time = timeToRedirect ? timeToRedirect : TIME_TO_REDIRECT  // eslint flags this line

想法是,如果参数timeToRedirect为零或未定义,我将分配一个常量TIME_TO_REDIRECT给变量time

但是 eslint 将此标记为违反规则 no-unneeded-ternary: 'Unnecessary use of conditional expression for default assignment'。

我当然可以改写成

let time = timeToRedirect;
if (!timeToRedirect) {
   time = TIME_TO_REDIRECT;
 }

但我认为它不那么优雅。

有没有更好的方法来重写三元表达式?

我目前正在使用这些 npm 包

"babel-eslint": "7.1.0",
"eslint": "3.9.1",
"eslint-config-airbnb": "12.0.0",
"eslint-plugin-import": "1.16.0",
"eslint-plugin-jsx-a11y": "2.2.3",
"eslint-plugin-react": "6.5.0",

【问题讨论】:

    标签: ecmascript-6 eslint eslint-config-airbnb


    【解决方案1】:

    They want you 使用OR operator

    const time = timeToRedirect || TIME_TO_REDIRECT;
    

    请注意,要捕获 undefined 值,您也可以在解构中使用默认初始化程序:

    render() {
        const { message, timeToRedirect: time = TIME_TO_REDIRECT } = this.props;
        …
    

    【讨论】:

    猜你喜欢
    • 2017-07-31
    • 2016-06-12
    • 2020-08-19
    • 2022-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2020-09-05
    相关资源
    最近更新 更多