【发布时间】:2019-12-22 08:04:12
【问题描述】:
滚动到底部以获得大部分解决方案 我留下这个帖子,以防其他人以后遇到同样的问题。
我正在按照初学者教程(来自 Wes Bos)学习 React,并且我已经三次检查我的代码是否与教程中的相同,但无论出于何种原因,它都会触发 ESlint 错误(即使,据说 ESlint 甚至没有安装在我的 VS Code 中)。
这是我的代码:
import React from "react";
import { formatPrice } from "../helpers";
class Order extends React.Component {
renderOrder = key => {
const fish = this.props.fishes[key];
const count = this.props.order[key];
const isAvailable = fish.status === 'available';
// /*eslint-disable */
if(!isAvailable) {
<li>
Sorry {fish ? fish.name : 'fish'} is no longer available
</li>
}
return (
<li>
{count} lbs of {fish.name}
{formatPrice(count * fish.price)}
</li>
);
// /*eslint-endisable */
};
render() {
const orderIds = Object.keys(this.props.order);
const total = orderIds.reduce((prevTotal,key) => {
const fish = this.props.fishes[key];
const count = this.props.order[key];
const isAvailable = fish && fish.status === 'available';
if(isAvailable) {
return prevTotal + (count * fish.price);
}
return prevTotal;
}, 0);
return (
<div className="order-wrap">
<h2>Order</h2>
<ul>
{orderIds.map(this.renderOrder)}
</ul>
<div className="total">
Total:
<strong>{formatPrice(total)}</strong>
</div>
</div>
);
}
}
export default Order;
我得到的错误是:
./src/components/Order.js 第 10 行:期望一个赋值或函数调用,而是看到一个表达式 no-unused-expressions
注意:第 10 行是我的 if 函数的开始
我尝试用谷歌搜索错误,但我想我太初学者了,无法理解我在这里找到的内容: https://eslint.org/docs/rules/no-unused-expressions
我能够通过在 if 函数周围使用 /*eslint-disable */ /*eslint-endisable */ 来让它运行(不是错误,虽然 if 函数似乎不起作用),但是我'还是想知道: 1、为什么会出现这个错误? 2. 为什么我之前在 VS 代码中禁用再卸载 ESlint 时会触发 ESlint 错误?
也尝试过清理一下代码,但还是不行:
// /*eslint-disable */
if (!isAvailable) {
<li>Sorry {fish ? fish.name : 'fish'} is no longer available</li>;
}
// /*eslint-endisable */
return (
<li>
{count} lbs {fish.name}
{formatPrice(count * fish.price)}
</li>
);
而且,如果我再看教程 30 秒,我就会找到 IF 函数为什么不起作用的答案,但我被 ESLint 错误难住了,我得到的并没有发生在教程视频中。我仍然不知道为什么我会收到 ESLint 错误,因为我没有安装它,更不用说启用了。
正确的代码需要返回:
renderOrder = key => {
const fish = this.props.fishes[key];
const count = this.props.order[key];
const isAvailable = fish.status === 'available';
if (!isAvailable) {
// added return below
return <li>Sorry {fish ? fish.name : 'fish'} is no longer available</li>;
}
return (
<li>
{count} lbs {fish.name}
{formatPrice(count * fish.price)}
</li>
);
};
【问题讨论】:
-
因为你不
return这个表达式它只是被执行并立即忘记
标签: reactjs visual-studio-code eslint