简体   繁体   English

带有条件的 React 中的 no-unused-expressions

[英]no-unused-expressions in React with conditionals

I have a form that needs to validate a const first, if true, open the modal, if false, submit the form.我有一个表单,需要先验证一个 const,如果为真,则打开模态,如果为假,则提交表单。

I did this, this works but I'm getting the error:我这样做了,这行得通,但我得到了错误:

Expected an assignment or function call and instead saw an expression @babel/no-unused-expressions预期分配或 function 调用,而是看到一个表达式 @babel/no-unused-expressions

modalOpen = () => this.setState({ showModal: true });

const validateType = !someAttribute && hasChange;

const submit = () => {
    validateType ? this.modalOpen() : handleSubmit();
};

// Do I need to have this submit here too?
<Form className={cn} onSubmit={isReadOnly ? () => {} : handleSubmit} readOnly={isReadOnly}>

    <Button
        type="button"
        onClick={submit}
    />
</Form>

The error occurs on this line here:错误发生在此行:

validateType ? this.modalOpen() : handleSubmit();

I looked at the documentation and I really don't understand why this error is happening.我查看了文档,我真的不明白为什么会发生这个错误。

If anyone can help me understand I would be very grateful.如果有人能帮助我理解,我将不胜感激。

Option 1 - replace ternary with if/else :选项 1 - 用if/else替换三元:

const submit = () => {
  if(validateType) this.modalOpen(); 
  else handleSubmit();
};

Option 2 - find the rule in your .eslint file, and change to rule to allow ternary expressions:选项 2 - 在.eslint文件中找到规则,然后更改为规则以允许三元表达式:

no-unused-expressions: ["error", { "allowTernary": true }]

Option 3 - ignore eslint for this line:选项 3 - 忽略此行的 eslint:

const submit = () => {
  // eslint-disable-next-line no-unused-expressions
  validateType ? this.modalOpen() : handleSubmit();
};

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

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