初始反应状态值可在chrome消息侦听器下的任何函数调用中访问

时间:2020-08-25 08:07:36

标签: reactjs google-chrome-extension use-effect use-state

因此,我对使用react js编写chrome扩展名有所了解。这种情况对我来说没有意义,因为从UI角度看,所有内容都按预期呈现。我在useEffect挂钩中附加了一个chrome消息侦听器,以便根据传递的消息执行操作。因此,例如,当满足我的切换条件chromeActions.SET_IMAGE_OBJECT_IN_DAILOG_APP时,我通过renderImageInApp函数更新了反应状态。根据这些状态更改,我的UI会按我预期的方式运行,但是,如果我console.log设置后立即让某个特定状态说imagObject,它将显示{{1} }和imgURL没有任何意义,因为如果imgId比我渲染imgURL组件的方式为空,它将永远不会渲染,但是会渲染。我有一个解决方法,我将所有状态值都传递给ImageCropper组件,并且那里还有另一个消息侦听器,它可以将该信息传递回后台脚本,并且可以再次由ImageCropper组件接收,而不是从中访问值DailoadApp State我使用这些传递的值,但是我认为这不是正确的方法。 谁能告诉我为什么我在DailogApp的消息侦听器中收到初始状态值而不是最新状态值?如果有更好的方法来做我想做的事?我曾尝试在DailogApp数组(第二个参数)中添加imagObject,但是由于某些原因,当我单击“保存”按钮时,它将图像保存两次。目前,我处于开发过程中,代码格式不佳,请不要判断。预先感谢任何可以提供帮助的人。

useEffects
import React, { useState, useEffect } from 'react'

//MUI
import { makeStyles } from "@material-ui/core";
import Grid from '@material-ui/core/Grid';
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";


// Helper Functions:
import { toggle } from './scripts/content/initiContent'
import { chromeActions, createMsgObjct } from './scripts/common/common'

import ImageCropper from './components/image_crop/ImageCropper'


const useStyles = makeStyles(theme => ({
    fullScreen: {
        height: '100%',
        width: '100%',
        margin: '0%'
    },
    controlsContainer: {
        width: '100%',
        marginTop: '0%',
    },
    toolbarButton: {
        backgroundColor: '#f0f0f7',
        width: '25%',
        borderRadius: '0px'
    },
    buttonLeft: {
        marginLeft: '2%'
    },
    buttonRight: {
        marginRight: '2%'
    },
    root: {
        width: '80%',
        height: '80%'
    }
}))

export default function DailogApp() {
    const saveButtonLabel = "Save" // INTERNATIONALIZATION_REQUIRED
    const cancelButtonLabel = "Cancel" // INTERNATIONALIZATION_REQUIRED
    const updateButtonLabel = "Update"// INTERNATIONALIZATION_REQUIRED
    const deleteButtonLabel = "Delete"// INTERNATIONALIZATION_REQUIRED
    const backToOriginalLabel = "Back to original" // INTERNATIONALIZATION_REQUIRED

    //States
    const [imagObject, setImagObject] = useState({
        imgURL: '',
        imgId: ''
    })
    const [showUpdateControls, setShowUpdateControls] = useState(false)
    const [finalCroppedImageURL, setFinalCroppedImageURL] = useState('')
    const [showBackToOriginal, setShowBackToOriginal] = useState(false)
    const [isFullScreenShot, setIsFullScreenShot] = useState(false)
    const [originalImageURL, setOriginalImageURL] = useState('')
    const [isExistingImage, setIsExistingImage] = useState(false)

    useEffect(() => {
        chrome.runtime.onMessage.addListener(
            (request, sender, sendResponse) => {
                switch (request.action) {
                    case chromeActions.SET_IMAGE_OBJECT_IN_DAILOG_APP: {
                        renderImageInApp(request.msgObject, false)
                        break;
                    }
                    case chromeActions.RENDER_EXISTING_SCREENSHOT:
                        renderImageInApp(request.msgObject, true)
                        toggle("aclipp-dailog-container")
                        break;
                    case chromeActions.SET_FINAL_IMG: {
                        setFinalImgURLAfterSaveClick(request.msgObject)
                    }
                    default:
                        return
                }
            }
        )
    }, [])

    const classes = useStyles();

    const renderImageInApp = (imgObject, _isExisitingImage) => {
        const { imgURL, imgId, fullScreenShot } = imgObject
        setIsFullScreenShot(fullScreenShot)
        setIsExistingImage(_isExisitingImage)
        console.log(imgObject) // This prints the values
        setImagObject({ ...imagObject, imgURL, imgId })
        console.log(imagObject)// prints empty imgURL, and imgId
        setOriginalImageURL(imgURL)
    }

    const reInitializeApp = () => {
        toggle("aclipp-dailog-container")
        toggle("aclipp-container")
        setImagObject({ ...imagObject, imgURL: '', imgId: '' })
        setFinalCroppedImageURL('')
        setOriginalImageURL('')
        setShowBackToOriginal(false)
        setIsFullScreenShot(false)
        setShowUpdateControls(false)
        setIsExistingImage(false)
    }

    const onCancelButtonClick = (e) => {
        e.preventDefault()
        reInitializeApp()
    }

    const sendFinalImageToBackGround = (message, imgObject) => {
        const finalImagelObject = {
            imgURL: imgObject.imgURL,
            imgId: imgObject.imgId,
            fullScreenShot: isFullScreenShot
        }
        console.log(finalImagelObject)
        chrome.runtime.sendMessage(createMsgObjct(message, finalImagelObject))
        reInitializeApp()
    }

    const onSaveClick = (e) => {
        e.preventDefault()
        chrome.runtime.sendMessage(createMsgObjct(chromeActions.GET_RESULTANT_CROPPED_IMG_URL))
    }

    const onDeleteClick = (e) => {
        e.preventDefault()
        chrome.runtime.sendMessage(createMsgObjct(chromeActions.DELETE_EXISTING_SCREEENSHOT, imagObject))
        reInitializeApp()
    }

    const setFinalImgURLAfterSaveClick = (imgObject) => {
        sendFinalImageToBackGround(isExistingImage ? chromeActions.UPDATE_EXISTING_SCREENSHOT : chromeActions.SAVE_SCREENSHOT, imgObject)
    }

    const onCropStartShowBackToOriginal = () => {
        setShowBackToOriginal(true)
        setShowUpdateControls(true)
    }

    const onBackToOriginalClick = () => {
        setShowBackToOriginal(false)
        setShowUpdateControls(false)
        const imgObject = {
            imgURL: originalImageURL,
            imgId: imagObject.imgId,
        }
        chrome.runtime.sendMessage(createMsgObjct(chromeActions.SET_CROPPER_BACK_TO_ORIGINAL_IMG, imgObject))
    }

    const onUpdateCropperClick = (e) => {
        e.preventDefault()
        chrome.runtime.sendMessage(createMsgObjct(chromeActions.UPDATE_IMAGE_TO_CROPP))
    }

    return (
        <Grid
            container
            className={classes.fullScreen}
            direction='column'
            justify="center"
            alignItems="center"
            spacing={3}
        >
            <Grid
                container
                className={classes.controlsContainer}
                direction='row'
                justify="center"
                spacing={1}
            >
                <Grid item xs={6} lg={6} sm={6}>
                    <Grid container justify='flex-end' >
                        <Button
                            variant="contained"
                            className={`${classes.toolbarButton} ${classes.buttonRight}`}
                            onClick={onCancelButtonClick}
                        >
                            {cancelButtonLabel}
                        </Button>
                    </Grid>
                </Grid>
                <Grid item xs={6} lg={6} sm={6}>
                    <Grid container
                        direction="row"
                        justify='flex-start' >
                        <Button
                            variant="contained"
                            className={`${classes.toolbarButton} ${classes.buttonLeft}`}
                            onClick={onSaveClick}
                        >
                            {saveButtonLabel}
                        </Button>
                        {
                            isExistingImage &&
                            <Button
                                variant="contained"
                                className={`${classes.toolbarButton} ${classes.buttonLeft}`}
                                onClick={onDeleteClick}
                            >
                                {deleteButtonLabel}
                            </Button>
                        }

                        {
                            showUpdateControls &&

                            <Button
                                variant="contained"
                                className={`${classes.toolbarButton} ${classes.buttonLeft}`}
                                onClick={onUpdateCropperClick}
                            >
                                {updateButtonLabel}
                            </Button>
                        }

                    </Grid>
                </Grid>
                {
                    showBackToOriginal &&
                    <Typography
                        style={{ cursor: 'pointer', color: 'white' }}
                        onClick={onBackToOriginalClick}
                    >
                        {backToOriginalLabel}
                    </Typography>
                }
            </Grid>
            {
                imagObject.imgURL !== '' &&
                <ImageCropper
                    src={imagObject.imgURL}
                    setFinalImgURLAfterSaveClick={setFinalImgURLAfterSaveClick}
                    onCropStartShowBackToOriginal={onCropStartShowBackToOriginal}
                    isFullScreenShot={isFullScreenShot}
                    imgId={imagObject.imgId}
                />
            }
        </Grid>
    )
}

0 个答案:

没有答案