首页 > 解决方案 > 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] });

标签: javascriptreactjsreact-native

解决方案


   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]);

推荐阅读