【问题标题】:Why do I get these errors with my ternary operator?为什么我的三元运算符会出现这些错误?
【发布时间】:2021-12-13 20:05:24
【问题描述】:

这是我在控制台中得到的:Unnecessary use of boolean literals in conditional expression no-unneeded-ternary.

我只是想做一个三元运算符来验证游戏的状态,并且只有当游戏已经开始并且 user.role 与玩家相等时,我才禁用按钮。我正在使用 reactjs,并在 FormField 钩子的帮助下制作了一个表单。

disabled ={(game.state === 'started' && user.role === PLAYER) ? true : false} 

【问题讨论】:

  • game.state === 'started' && user.role === PLAYER 已经计算为布尔值。

标签: javascript reactjs conditional-statements conditional-operator


【解决方案1】:

三元运算符是不必要的:

disabled ={(game.state === 'started' && user.role === PLAYER)} 

【讨论】:

  • 谢谢你!现在我明白了:TypeError: Cannot read properties of undefined (reading 'state')
  • @Joe 表示gameundefined
【解决方案2】:

在这种情况下不需要使用语句,ESlint 让你知道它是多余的,因为从该语句产生的值已经是一个布尔值,你可以创建一个更简单的代码。

只写:

disabled = {(game.state === 'started' && user.role === PLAYER)}

【讨论】:

    猜你喜欢
    • 2013-11-09
    • 2019-09-17
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    相关资源
    最近更新 更多