javascript - React Native:将状态函数转换为钩子时遇到问题
问题描述
尝试将 this.state 函数或代码集转换为钩子时遇到了麻烦,因为我相信钩子更整洁和直接。这是代码:
state = {
captures: [],
// setting flash to be turned off by default
flashMode: Camera.Constants.FlashMode.off,
capturing: null,
// start the back camera by default
cameraType: Camera.Constants.Type.back,
};
setFlashMode = (flashMode) => this.setState({ flashMode });
setCameraType = (cameraType) => this.setState({ cameraType });
handleCaptureIn = () => this.setState({ capturing: true });
handleCaptureOut = () => {
if (this.state.capturing)
this.camera.stopRecording();
};
handleShortCapture = async () => {
const photoData = await this.camera.takePictureAsync();
this.setState({ capturing: false, captures: [photoData, ...this.state.captures] })
};
handleLongCapture = async () => {
setTimeout(() => this.state.capturing && this.camera.stopRecording(), 20*1000);
const videoData = await this.camera.recordAsync();
this.setState({ capturing: false, captures: [videoData, ...this.state.captures] });
解决方案
const [captures, setCaptures] = useState([]);
const [flashMode, setFlashMode] = useState(Camera.Constants.FlashMode.off);
const [capturing, setCapturing] = useState(false);
const [cameraType, setCameraType] = useState(Camera.Constants.Type.back);
const setFlashModehandler = (flashMode) => setFlashMode(flashMode);
const setCameraTypeHandler = (cameraType) => setCameraType(cameraType);
const handleCaptureInHandler = () => setCapturing(true);
const handleCaptureOut = () => {
if (capturing)
camera.stopRecording();
};
const handleShortCapture = async () => {
const photoData = await camera.takePictureAsync();
setCapturing(false);
setCaptures([...captures, photoData]);
};
const handleLongCapture = async () => {
setTimeout(() => capturing && camera.stopRecording(), 20*1000);
const videoData = await camera.recordAsync();
setCapturing(false);
setCaptures([...captures, videoData]);
推荐阅读
- python - 启动 Python REPL 并执行命令
- html - 溢出:隐藏在 div 上
- excel - Excel VBA .Formula - 添加对单元格的绝对引用的语法错误
- blazor - 如何在继承的组件中自动设置事件回调?
- javascript - Vue JS 动态改变 img
- android - DownloadManager 无法创建目标文件/E/cutils:|无法创建 mkdirat | 无法确保目录 |SDK<21
- mysql - NodeJS / MariaDB 连接器——createConnection() 没有返回正确的连接对象
- c# - Azure 语音认知 (TTS) 限制信息
- r - 从 r markdown 编织到 pdf 时的调试问题
- algorithm - Big Oh Notation 查找 n0 和 c