【发布时间】:2022-01-09 09:33:11
【问题描述】:
我有一个导出承诺的组件 MicButtons.js
import Voice from 'react-native-voice'
export const MicButton = async () => {
Voice.start('en-US')
Voice.onSpeechResults = async (res) => {
res = await JSON.parse(JSON.stringify(res)).value[0]
return res
}
}
当我尝试在另一个组件中使用它时,等待不起作用并且警报显示“未定义”
import MyButton from '../components/MyButton';
import { MicButton } from '../components/MicButton';
//...
<MyButton h="80%" w="50%" srcImg={mic} func={async() => {
let command = await MicButton()
alert(command)
}}></MyButton>
这是MyButton 组件的样子:
import React from 'react';
import PropTypes from 'prop-types'
import { Text, View, TouchableOpacity, ImageBackground } from 'react-native';
const MyButton = ({ text="", h, w, srcImg, func=()=>{} }) => {
return (
<View style={{height: h, width: w}}>
<TouchableOpacity style={{ height: '100%', width: '100%'}} onPress={func}>
<ImageBackground source={srcImg} style={{flex: 1}}>
<Text>{text}</Text>
</ImageBackground>
</TouchableOpacity>
</View>
)
}
MyButton.PropTypes = {
text: PropTypes.string,
h: PropTypes.number,
w: PropTypes.number,
srcImg: PropTypes.object,
func: PropTypes.func
}
export default MyButton
【问题讨论】:
-
MicButton不返回任何内容 -
您的
MicButton()函数没有返回值,因此您的命令未定义。Voice.onSpeechResults = ...为这个属性分配了一个函数,但你没有在这里调用它。 -
JSON.parse 不是异步等待没有意义。
-
export const MicButton = async () => { return new Promise((resolve) => { Voice.start('en-US') Voice.onSpeechResults = async (res) => { res = await JSON.parse(JSON.stringify(res)).value[0] resolve(res); } }});}
标签: javascript react-native async-await promise