typescript - “声音”类型的参数不可分配给“SetStateAction”类型的参数'
问题描述
我正在使用 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
解决方案
由于您将sound
状态初始化为 undefined ( 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!
推荐阅读
- c++ - C++ - 从派生类中提取模板参数
- c# - 在 C# 中使用命名管道传递消息客户端和服务器
- android - 在我的 Android 应用程序上处理来自 Android TV Box 中鼠标指针的用户输入
- python - 如何在 google colab it 中访问网络摄像头以获取以下代码
- c++ - C++ std::conditional_variable::wait()
- html - 如何在 NodeJS 的 post 请求中触发网页?
- python - 如何将 Numpy 数组传递给只需要一个参数的 lambda 函数?
- angular - 使用来自 ngFor 的值更新 Div 属性
- javascript - 如何在 ReactJs 中使用基于 VueJs 的 Web 组件
- angular - NullInjectorError:没有 NbDialogRef 的提供者!在星云对话服务中