您好,我是React和编码的新手.我正在关注在线教程以学习React并遇到错误
./src/components/counter.jsx Line 24: 'product' is not defined no-undef
您能否简单地解释出什么问题了,所以我知道如何解决这个问题,下次遇到它时可以解决.
我仔细阅读了所有有关*的相关问题,但仍无法解决,如果我错过了回答此问题的问题,请链接它.
我过去曾犯过这个错误,但通常这只是因为我有错字(例如大写字母而不是小写字母)或未正确输入某些内容,但是据我所知这次不是这种情况.
我的代码与视频中的代码没有区别.
=== index.js ===
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
//import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "bootstrap/dist/css/bootstrap.css";
import Counters from "./components/Counters";
ReactDOM.render(<Counters />, document.getElementById("root"));
serviceWorker.unregister();
=== counter.jsx ===
import React, { Component } from "react";
class Counter extends Component {
state = {
count: 0
};
handleIncrement = product => {
console.log(product);
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button
onClick={() => this.handleIncrement(product)} //this is the line with the error
className="btn btn-secondary btn-sm"
>
Increment
</button>
</div>
);
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.count === 0 ? "warning" : "primary";
return classes;
}
formatCount() {
const { count } = this.state;
return count === 0 ? "Zero" : count;
}
}
export default Counter;
=== counters.jsx ===
import React, { Component } from "react";
import Counter from "./counter";
class Counters extends Component {
state = {};
render() {
return (
<div>
<Counter />
<Counter />
<Counter />
<Counter />
</div>
);
}
}
export default Counters;
预期的输出是,当我运行它并转到网页时,它具有可以按的按钮和旁边的计数器,这些计数器将显示已被按下的次数.
实际发生的是,当我转到页面时,它显示以下内容:
Failed to compile
./src/index.js
Cannot find file: 'Counters.jsx' does not match the corresponding name on disk: './src/components/counters.jsx'.
This error occurred during the build time and cannot be dismissed.
解决方法:
onClick={() => this.handleIncrement(product)}
在执行此操作时,产品不存在.该变量尚未在任何地方声明或分配,因此未定义消息.
此消息是像eslint这样的短绒的产物,其中:
is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code, with the goal of making code more consistent and avoiding bugs.
短绒可以配置为发出警告和错误,并且在用作构建或编译过程的一部分时,可以配置为中止编译.
我不确定这里的意图是什么,但是您可以改为使用onClick = {this.handleIncrement},它将增加您的计数器.