【发布时间】:2018-08-24 16:25:39
【问题描述】:
我有一个 reactJS 应用程序,它从服务中查找条形码。如果在服务上找不到条形码,我会向用户呈现一条错误消息,我还会呈现一个输入框和一个按钮,并提示用户手动输入条形码。这是我正在执行的代码:
import React from 'react';
import '../styles/app.css';
class Lookupbarcode extends React.Component {
constructor(props) {
super(props);
this.state = {
barcode: '',
};
}
barcodeLookup(passedBarcode) {
let currentComponent = this;
let url = "https://cors-anywhere.herokuapp.com/http://api.barcodelookup.com/v2/products?barcode=" + passedBarcode + "&key=mj1pm32ylcctxj1byaia85n9dk2d4i";
const options = { method: 'GET' };
currentComponent.setState({ barcode: passedBarcode });
fetch( url, options)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
if (myJson == undefined)
{
console.log("fetch failed")
}
else
{
//inspect the data that the WebAPI returned
var product_string = encodeURI(myJson.products[0].product_name);
location.href="./ebaylookup?" + product_string + "&" + passedBarcode;
}
});
}
componentWillMount() {
var barcodeParm = this.props.location.search.substring(1);
this.barcodeLookup(barcodeParm);
}
manuallLookup() {
var manualBarCode = document.getElementById("manualBarcode").value;
console.log("manual lookup: ", manualBarCode);
this.barcodeLookup(manualBarCode);
}
render() {
return (
<div>
<div>
<label id="errorFont">Barcode {this.state.barcode} was not found by our barcode service. You can re-scan your barcode or enter a barcode below</label>
</div>
<div>
<button className="btnStartScan"
type='button'
onClick={() => {
location.href = ('/newscan')
}}>
Re-Scan
</button>
</div>
<div>
<center><label className="appDescription">OR</label></center>
</div>
<div id="errorDivInput">
<center><input className="revisedProductName" id="manualBarcode"/></center><br />
</div>
<div>
<button className="btnStartScan" onClick={this.manuallLookup}>
Manually Lookup
</button>
</div>
</div>
);
}
}
export default Lookupbarcode;
用户可以选择单击一个按钮,该按钮将转到不同的页面 (/newscan) 或在输入框中手动输入条形码。如果用户在输入框中输入条码并点击“Manually Lookup”按钮,我会执行一个名为manualLookup的函数。
manualLookup 应该获取用户输入的条形码值并将该值传递给函数barcodeLookup 以查看是否在条形码服务中找到了手动输入的条形码。
当我执行代码时,手动输入条形码,然后单击手动查找按钮,我在控制台日志中收到以下错误消息:
未捕获的类型错误:无法读取未定义的属性“barcodeLookup”
导致错误的行是这样的:
this.barcodeLookup(manualBarCode);
当我查看控制台日志时,我看到它是在 manualLookup 函数中生成的:
manual lookup: 13131313131313131312
那么,当我能够在 componentWillMount() 中以完全相同的方式引用 this.barcodeLookup() 时,为什么我无法引用它?
感谢您的帮助。
【问题讨论】:
标签: reactjs