Arrow function should not return assignment no-return-assign

三世轮回 提交于 2021-02-10 11:48:31

问题


My code is working correctly in the app however, before commit husky runs and gives out the error saying "Arrow function should not return assignment no-return-assign"

           <Field name='dob' label='dateOfBirth'
              placeholder=''
              onFocus={(e) => e.target.placeholder = 'MM/YYYY/DD'}
            />

回答1:


As several people mention in comments, the issue is that you're using

(e) => e.target.placeholder = 'MM/YYYY/DD'

which is roughly equivalent to

anon_func = function (e) {
    return e.target.placeholder = 'MM/YYYY/DD';
}

because (args) => <expression> means to evaluate the expression and return the result.

Contrary to jakemingolla's answer, this is legal; it returns 'MM/YYYY'DD' which doesn't matter in this situation since you don't care about any return value. That's why it "works". But it is generally regarded as poor style, which is why your pre-commit checks flag it.

What you want is (args) => {<function-body>}, which (like any directly-declared function body) just returns undefined if you don't explicitly return something. That is

(e) => {e.target.placeholder = 'MM/YYYY/DD';}

is roughly like

anon_func = function (e) {
    e.target.placeholder = 'MM/YYYY/DD';
}

which is what you want.




回答2:


If you omit the brackets in your arrow function, it will implicitly return the statement. In this case, the compiler is warning you that you are returning the assignment, which is not allowed (I'm guessing to avoid a situation where you are attempting to check for equality and mistakenly type only a single = instead of ===)

You can surround the function body in brackets to avoid this issue:

onFocus={(e) => { e.target.placeholder = 'MM/YYYY/DD'} }

Check out the MDN for more information on arrow functions.



来源:https://stackoverflow.com/questions/55974912/arrow-function-should-not-return-assignment-no-return-assign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!