解决React报错Expected an assignment or function call and instead saw an expression

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

解决React报错Expected an assignment or function call and instead saw an expression

Borislav Hadzhiev   2022-12-02 我要评论

正文

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

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

// 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来解决这个错误。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们