目录
  • 正文从这开始~
  • 总览
  • 显式返回
  • 隐式返回
  • 返回对象

正文从这开始~

总览

当我们忘记从函数中返回值时,会产生"Expected an assignment or function call and instead saw an expression"错误。为了解决该错误,确保显式地使用return语句或使用箭头函数隐式返回。

React报错信息之Expected an assignment or function call and instead saw an expression

下面有两个示例来展示错误是如何产生的。

// App.js

const App = props => {
  const result = ['a', 'b', 'c'].map(el => {
    // ⛔️ Expected an assignment or function call and instead saw an expression. eslint no-unused-expressions
    el + '100';
  });

  return <div>hello world</div>;
};

const mapStateToProps = (state) => {
  // ⛔️ Expected an assignment or function call and instead saw an expression. eslint no-unused-expressions
  todos: ['walk the dog', 'buy groceries']
}

export default App;

App组件中,错误是在Array.map()方法中引起的。这里的问题在于,我们没有从传递给map()方法的回调函数中返回任意值。

在JavaScript函数中,如果我们没有显式地使用return语句,或者使用箭头函数隐式地返回一个值,则返回undefined

mapStateToProps函数中的问题是一样的,我们忘记从函数中返回值。

显式返回

为了解决该错误,我们必须显式地使用return语句或使用箭头函数隐式返回值。

下面是一个例子,用来说明如何使用显式return来解决这个错误。

const App = props => {
const result = ['a', 'b', 'c'].map(el => {
return el + '100'; //

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。