注释从这开始~

总览

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

上面有两个示例来展现谬误是如何产生的。

// App.jsconst 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'; // ️ using explicit return  });  console.log(result);  return <div>hello world</div>;};const mapStateToProps = state => {  return {todos: ['walk the dog', 'buy groceries']}; // ️ using explicit return};export default App;

咱们通过在map()办法中显式返回来解决问题。这是必须的,因为Array.map办法返回一个数组,其中蕴含咱们传递给它的回调函数所返回的所有值。

须要留神的是,当你从一个嵌套函数中返回时,你并没有同时从外层函数中返回。

隐式返回

另一种办法是应用箭头函数的隐式返回。

// ️ implicit returnconst App = props => (  <div>    <h2>hello</h2>    <h2>world</h2>    {['a', 'b', 'c'].map(element => (      <div key={element}>{element}</div>    ))}  </div>);// ️ implicit returnconst result = ['a', 'b', 'c'].map(element => element + '100');console.log(result); // ️ ['a100', 'b100', 'c100']// ️ implicit returnconst mapStateToProps = state => ({  todos: ['walk the dog', 'buy groceries'],});export default App;

咱们为App组件应用了隐式地箭头函数返回。

须要留神的是,咱们基本没有应用大括号。简短的隐式返回应用圆括号。

返回对象

如果咱们应用隐式返回来返回一个对象,咱们必须用圆括号来包裹这个对象。

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

一个简略的思考形式是--当你应用大括号而没有用圆括号包裹它们时,你是在申明一个代码块(比方if语句)。

{  console.log('this is my block of code');}

当不应用圆括号时,你有一个代码块,而不是一个对象。

但当你用圆括号包裹住大括号时,你就有一个隐式的箭头函数返回。

如果你认为eslint规定不应该在你的计划中造成谬误,你能够通过应用正文来敞开某一行的eslint规定。

// eslint-disable-next-line no-unused-expressions

正文应该放在造成谬误的那一行的正上方。