【发布时间】:2019-06-17 14:51:34
【问题描述】:
我有三种方法:
isSixCharactersLong(event) {
const input_len = event.target.value.length;
if (input_len === 6) {
this.setState({isSixCharactersLong: true})
} else {
this.setState({isSixCharactersLong: false})
}
}
isAlphanumeric(event) {
const input_str = event.target.value;
for (let i = 0; i < input_str.length; i++) {
const code = input_str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
this.setState({isAlphanumeric: true});
} else {
this.setState({isAlphanumeric: false});
}
}
}
isEmpty(event) {
event.target.value ? this.setState({inputIsBlank: false}) : this.setState({inputIsBlank: true});
}
我想做的是在这三种方法解决后运行一个函数。于是我写了以下内容:
async handleValidation(e) {
this.isAlphanumeric(e);
this.isEmpty(e);
this.isSixCharactersLong(e);
}
然后我有了这个由我的 React 应用程序触发的最终方法。
handleOnChange = async (e) => {
await this.handleValidation(e)
.then(() => this.setState({code: e.target.value}))
};
我认为这会起作用,但我不断收到 e 为 null 的错误。不知何故,我失去了事件。
我认为问题在于,我没有使用 async 并等待正确的方法。
【问题讨论】:
-
为什么是
handleValidation一个async函数?它没有await或return任何东西,它调用的函数也不是异步的。 -
非异步函数没有异步和等待的意义......
-
-
最后是眨眼表情
-
您不熟悉它们并不重要 - 您可以不使用它们。他们在这里根本没有帮助你。只需编写普通函数,您所做的一切除了
setState内部发生的事情现在都是同步的。
标签: javascript reactjs promise async-await es6-promise