使用APlayer自动获取颜色的问题

问题

在使用APlayer官网配置自适应主题色的配置时,出现歌单列表选中其他歌曲无反应的情况;检查网页发现报错:

1
[Error] TypeError: undefined is not an object (evaluating 'ap.list.audios[index].theme')

原因

以下为官方文档提供的源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const ap = new APlayer({
--snip--
});
--snip--

const setTheme = (index) => {
if (!ap.list.audios[index].theme) {
xhr.onload = function(){
--snip--
}
};
setTheme(ap.list.index);
ap.on('listswitch', (index) => {
setTheme(index);
});

注:ap为定义的APlayer播放器对象

在第36行中,将ap.list.index传入了setTheme函数,在第20行定义的setTheme函数中使用index的值作为ap.list.audios这个列表的索引。整个函数完成后将这个函数绑定到APlayer的listswitch事件上(切换歌曲事件),这样每当切换歌曲就会执行一遍这个函数进行设置主题色。

在这个过程中,index是一个字典(具体上为:{index: n}),而操作audios[index]则是将这个字典作为列表的索引获取元素,由于JavaScript无法处理这样的操作,便将整个audios[index]作为undefined进行返回,而之后读取其属性.theme则报错undefined is not an object

解决方法

在这里,我们只需要修改一处即可完成修复。

setTheme传入index的时候,我们只需要将字典index中的键index对应的取出并传入setTheme即可解决问题,具体如下:

1
2
3
ap.on('listswitch', (index) => {
setTheme(index.index); // 此处将index改为index.index
});