如何避免 eslint 规则 no-unneeded-ternary violation:'Unnecessary use of conditional expression for default assignment'
How to avoid eslint rule no-unneeded-ternary violation: 'Unnecessary use of conditional expression for default assignment'
这是我的代码
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",
They want you to use the OR operator:
const time = timeToRedirect || TIME_TO_REDIRECT;
请注意,要捕获 undefined
值,您还可以在解构中使用默认初始化程序:
render() {
const { message, timeToRedirect: time = TIME_TO_REDIRECT } = this.props;
…
这是我的代码
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",
They want you to use the OR operator:
const time = timeToRedirect || TIME_TO_REDIRECT;
请注意,要捕获 undefined
值,您还可以在解构中使用默认初始化程序:
render() {
const { message, timeToRedirect: time = TIME_TO_REDIRECT } = this.props;
…