【问题标题】:Argument of type 'Sound' is not assignable to parameter of type 'SetStateAction<undefined>'“声音”类型的参数不能分配给“SetStateAction<undefined>”类型的参数
【发布时间】:2021-12-04 17:19:57
【问题描述】:

我正在使用 typescript 和 expo-cli 编写一个简单的 react-native 应用程序。 我已经导入了 expo-av,但在尝试播放音频时遇到了一些问题。 我正在关注 [this guide][1],但它是用 javascript 编写的,我想这就是问题所在,因为它在抱怨类型。

  import { Audio } from "expo-av";
  
  export const useAudio = () => {
    const [sound, setSound] = useState();

    const playSound = async () => {
        const { sound } = await Audio.Sound.createAsync( // this line causes the error
        require("../assets/sound/ding.mp3")
      );
    setSound(sound);
    await sound.playAsync();
  }
};

[![error message][2]][2]


  [1]: https://docs.expo.dev/versions/v42.0.0/sdk/audio/
  [2]: https://i.stack.imgur.com/PqDgC.png

【问题讨论】:

  • playSound 的调用在哪里?
  • @AlexShtromberg 因为我在函数中遇到错误,所以此时无处可去。

标签: typescript react-native expo expo-av


【解决方案1】:

由于您将 sound 状态初始化为未定义 (useState()),Typescript 不允许将 sound 设置为任何其他类型。

我建议你这样输入sound

    const [sound, setSound] = useState<Audio.Sound|null>(null);

所以,sound 最初是 null,但可以根据组件的逻辑设置为 Audio.Sound 类型的另一个对象。这要求您在使用其任何属性之前始终小心 sound 是否为 null

例如:

sound.play() // first check if it isn't null!

【讨论】:

    猜你喜欢
    • 2020-11-20
    • 1970-01-01
    • 2021-05-16
    • 2022-11-12
    • 2021-12-04
    • 2021-03-08
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    相关资源
    最近更新 更多