我在React Native中构建一个简单的计算器作为第一个项目。我有一切运作。但是,当我按下等号按钮而没有数字时,我得到一个错误,'脚本的意外结束'。所以我在评估之前添加了一个验证函数来检查最后一个输入。但我仍然收到错误消息。
即使我只是尝试在最后一个字符不是数字时控制日志,我仍然会收到错误。我无法弄清楚它是什么。有什么想法吗?很多Google搜索和StackOverflow对我来说都是空的。代码和错误如下。
我的按钮代码。
import React, { Component } from 'react';
import { Text, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import * as actions from '../actions';
class Button extends Component {
// Validate last character is number before evaluating expression
validateInput(data) {
let rawData = this.props.rawData;
let lastChar = rawData.substr(rawData.length - 1);
lastChar !== isNaN ? this.props.newResult(eval(rawData)) : console.log(lastChar);
}
handleLongPress(data) {
data === 'DEL' ? this.props.clearAll() : console.log('Not delete');
}
handleOnPress(data) {
switch (data) {
case '=':
this.validateInput(data);
break;
case 'DEL':
this.props.removeInput();
break;
default:
this.props.addInput(data);
}
}
render() {
let { value, parentStyles, childStyles, text, onLongPress } = this.props
return (
<TouchableOpacity
onPress={() => this.handleOnPress(value)}
onLongPress={() => this.handleLongPress(value)}
style={parentStyles}>
<Text
style={childStyles}
>{text}
</Text>
</TouchableOpacity>
);
}
}
const mapStateToProps = ({ rawData }) => ({
rawData,
})
export default connect(mapStateToProps, actions)(Button);
错误消息:
Unexpected end of script
validateInput
hashAssetFiles:100008:53
handleOnPress
hashAssetFiles:100020:29
onPress
hashAssetFiles:100045:40
touchableHandlePress
hashAssetFiles:40117:45
_performSideEffectsForTransition
hashAssetFiles:39731:34
_receiveSignal
hashAssetFiles:39668:44
touchableHandleResponderRelease
hashAssetFiles:39557:24
invokeGuardedCallback
hashAssetFiles:35129:19
invokeGuardedCallbackAndCatchFirstError
hashAssetFiles:35151:64
executeDispatch
hashAssetFiles:35180:128
executeDispatchesInOrder
hashAssetFiles:35188:48
executeDispatchesAndRelease
hashAssetFiles:35254:58
forEachAccumulated
hashAssetFiles:35248:37
processEventQueue
hashAssetFiles:35323:143
runEventQueueInBatch
hashAssetFiles:35612:79
handleTopLevel
hashAssetFiles:35617:29
<unknown>
hashAssetFiles:35749:51
perform
hashAssetFiles:36164:99
batchedUpdatesWithControlledComponents
hashAssetFiles:35697:30
_receiveRootNodeIDEvent
hashAssetFiles:35748:46
receiveTouches
hashAssetFiles:35763:173
__callFunction
hashAssetFiles:6616:47
<unknown>
hashAssetFiles:6432:29
__guard
hashAssetFiles:6587:11
callFunctionReturnFlushedQueue
hashAssetFiles:6431:20
答案 0 :(得分:0)
如果有人遇到过类似的事情,我终于想出了问题。基本上它只是一个弱脑力的时刻。 rawData
是一个字符串。评估最后一个字符是否是一个数字总是很糟糕。相反,我决定检查最后一个字符是否在包含运算符的数组中。这是我所做的改变。
// Validate last character is number before evaluating expression
validateInput(data) {
const operators = ['*', '/', '+', '-', '%']
let rawData = this.props.rawData;
let lastChar = rawData.substr(rawData.length - 1);
if (operators.includes(lastChar)) {
return null;
} else {
this.props.newResult(eval(rawData));
}
}