HarmonyOS鸿蒙Next中ForEach循环AudioDeviceDescriptors报TypeError is not callable
HarmonyOS鸿蒙Next中ForEach循环AudioDeviceDescriptors报TypeError is not callable
import { audio } from '@kit.AudioKit'; // 导入audio模块。
import DeviceCard from '../components/DeviceCard';
let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
let audioDevices:audio.AudioDeviceDescriptors;
audioRoutingManager.getDevices(audio.DeviceFlag.INPUT_DEVICES_FLAG).then((data: audio.AudioDeviceDescriptors) => {
audioDevices=data
});
@Component
export default struct DeviceSelection {
build() {
RelativeContainer() {
ForEach(audioDevices,(item:audio.AudioDeviceDescriptor)=>{
DeviceCard({deviceName:item.name})
})
}
.height('100%')
.width('100%')
}
}
代码如上
更多关于HarmonyOS鸿蒙Next中ForEach循环AudioDeviceDescriptors报TypeError is not callable的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,ForEach
循环AudioDeviceDescriptors
报TypeError
is not callable是因为AudioDeviceDescriptors
不是可迭代对象或回调函数使用不当。确保AudioDeviceDescriptors
是数组类型,且ForEach
的第一个参数正确传递了回调函数。检查AudioDeviceDescriptors
数据格式是否符合要求,正确用法示例:ForEach(this.audioDevices, (item) => {...})
。
更多关于HarmonyOS鸿蒙Next中ForEach循环AudioDeviceDescriptors报TypeError is not callable的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,您遇到的TypeError问题是因为ForEach组件不能直接使用异步获取的audioDevices数组。问题出在audioDevices初始时是undefined,而ForEach要求数据源必须是一个已初始化的数组。
正确的做法应该是:
- 使用@State装饰器管理audioDevices状态
- 确保在组件初始化时完成数据加载
修改后的代码示例:
import { audio } from '@kit.AudioKit';
import DeviceCard from '../components/DeviceCard';
@Component
export default struct DeviceSelection {
[@State](/user/State) audioDevices: audio.AudioDeviceDescriptors = [];
aboutToAppear() {
audio.getAudioManager()
.getRoutingManager()
.getDevices(audio.DeviceFlag.INPUT_DEVICES_FLAG)
.then((data) => {
this.audioDevices = data;
});
}
build() {
RelativeContainer() {
ForEach(this.audioDevices, (item: audio.AudioDeviceDescriptor) => {
DeviceCard({deviceName: item.name})
})
}
.height('100%')
.width('100%')
}
}
关键修改点:
- 将audioDevices声明为@State装饰的组件状态
- 在aboutToAppear生命周期中加载设备数据
- 确保ForEach使用的数据源是响应式的状态变量