React報錯之Expected an assignment or function call and instead saw an expression
- 2022 年 8 月 19 日
- 筆記
正文從這開始~
總覽
當我們忘記從函數中返回值時,會產生”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
來解決這個錯誤。
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 return
const App = props => (
<div>
<h2>hello</h2>
<h2>world</h2>
{['a', 'b', 'c'].map(element => (
<div key={element}>{element}</div>
))}
</div>
);
// 👇️ implicit return
const result = ['a', 'b', 'c'].map(element => element + '100');
console.log(result); // 👉️ ['a100', 'b100', 'c100']
// 👇️ implicit return
const mapStateToProps = state => ({
todos: ['walk the dog', 'buy groceries'],
});
export default App;
我們為App
組件使用了隱式地箭頭函數返回。
需要注意的是,我們根本沒有使用大括弧。簡短的隱式返回使用圓括弧。
返回對象
如果我們使用隱式返回來返回一個對象,我們必須用圓括弧來包裹這個對象。
// ✅ RIGHT
const mapStateToProps = state => ({
todos: ['walk the dog', 'buy groceries'],
});
// ⛔️ WRONG
const 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
注釋應該放在造成錯誤的那一行的正上方。