Gutenberg块属性,不保存随机值

问题描述 投票:0回答:1

我需要为gutenberg块提供一个唯一的ID,但是由于我没有找到一种简便的方法,因此我选择使用随机值来获得一个可能唯一的数字(我必须非常不幸)使其在同一页面中两次生成相同的数字)。

但是有一个问题...每次保存块时,它都会损坏,因为每次都会重新创建ID,即使这只是默认值,也很难,所以只有在刚刚创建块时才应使用它。

这是我的方块:

registerBlockType('materialize-fcd/gallery-block', {
    title: "Material Gallery - Galleria",
    icon: 'images-alt',
    category: 'common',

    attributes: {
        images: {
            type: 'array',
            default: null
        },
        ids: {
            type: 'array',
            default: null
        },
        size: {
            type: 'string',
            default: 'full'
        },

        s: {
            type: 'number',
            default: 6
        },
        m: {
            type: 'number',
            default: 4
        },
        l: {
            type: 'number',
            default: 3
        },
        lightbox:{
            type: 'string',
            default: 'gal_'+Math.floor(Math.random() * 9000)
        }
    },


    edit(props) {
        const {
            setAttributes,
            attributes,
        } = props;

        function changeS(newValue) {
            setAttributes({
                s: newValue
            })
        }
        function changeM(newValue) {
            setAttributes({
                m: newValue
            })
        }
        function changeL(newValue) {
            setAttributes({
                l: newValue
            })
        }
        function onChangeSize(value) {
            setAttributes({
                size: value
            })
        }
        function onChangeLightbox(value) {
            setAttributes({
                lightbox: value
            })
        }


        function onImagesSelect(imageObject) {
            var id_array = imageObject.map(image => image.id);
            setAttributes({
                images: imageObject,
                ids: id_array
            })
            console.log(attributes.images);
        }


        var choices = [];
        if (attributes.images != null) {
            //ciclo le immagini
            for(var i in attributes.images){
                //ciclo le sizes
                for (var name in attributes.images[i].sizes) {

                    if (!choices.map(choice=>choice.value).includes(name)){
                        var choice = {
                            value: name,
                            label: name
                        }
                        if(name == attributes.size) choice.selected = true;
                        choices.push(choice);
                    }

                }
            }
        }

        var mediaButton = (<MediaUpload  onSelect={onImagesSelect} type="image"
                                    value={attributes.ids}
                                    render={ ({ open}) => { return (
                                        <button onClick={open}>
                                            Choose image
                                        </button>);
                                        }
                                    }
                                    multiple = 'add'
                                    />);
        var images = [];
        for (var i in attributes.images) {
            images.push(<img style={{"max-width" : "150px", "max-height" : "150px"}} src={attributes.images[i].sizes.full.url}/>);
        }

        return ([(
                    <InspectorControls>
                        <PanelBody title='Column Size'>
                            <PanelRow>
                                <RangeControl
                                    label="Mobile (S)"
                                    value={ attributes.s }
                                    onChange={changeS}
                                    min={ 0 }
                                    max={ 12 }
                                    />
                            </PanelRow>
                            <PanelRow>
                                <RangeControl
                                    label="Tablets (M)"
                                    value={ attributes.m }
                                    onChange={changeM}
                                    min={ 0 }
                                    max={ 12 }
                                    />
                            </PanelRow>
                            <PanelRow>
                                <RangeControl
                                    label="Desktops (L)"
                                    value={ attributes.l }
                                    onChange={changeL}
                                    min={ 0 }
                                    max={ 12 }
                                    />
                            </PanelRow>
                        </PanelBody>
                        <PanelBody title='Image Size'>
                            <PanelRow>
                                <SelectControl
                                            label='Image size:'
                                            value={attributes.size}
                                            onChange={onChangeSize}
                                            options={choices}
                                            />
                            </PanelRow>
                        </PanelBody>
                        <PanelBody title='Lightbox'>
                            <PanelRow>
                                <TextControl
                                            label='Gallery ID:'
                                            value={attributes.lightbox}
                                            onChange={onChangeLightbox}
                                            />
                            </PanelRow>
                        </PanelBody>
                        <PanelBody title='Images'>
                            <PanelRow>
                                {mediaButton}
                            </PanelRow>
                        </PanelBody>
                    </InspectorControls>
                    ),(
                    <div>

                    {attributes.className ?'CLASS: ' + attributes.className : null}
                    {attributes.className ?<br/> : null}
                    {mediaButton}
                    <br/>
                    {attributes.images != null ? images : ''}
                    </div>
                    )]);
    },

    save(props) {

        const { attributes, className } = props;
        var images = [];
        var cols = (props.attributes.s != 0 ? ' s' + props.attributes.s : '') + (props.attributes.m != 0 ? ' m' + props.attributes.m : '') + (props.attributes.l != 0 ? ' l' + props.attributes.l : '') + (props.attributes.className ? ' '+props.attributes.className : '');

        for (var i in attributes.images) {
            images.push(
                <div class={'col' + cols}>
                    <a sl={(attributes.lightbox == '' || attributes.lightbox == null) ? null : attributes.lightbox} href={attributes.images[i].sizes.full.url} class={(attributes.className ? attributes.className + ' ' : '')+'waves-effect waves-light img gal z-depth-2'}>
                        <img src={attributes.images[i].sizes[attributes.size].url} />
                    </a>
                </div>
            );
        }
        return (
            <div class="row">
                {images}
            </div>
        );
    }
})

这是我得到的错误:

Block validation failed
Content generated by `save` function:

<div class="row" class="wp-block-materialize-fcd-gallery-block"><div class="col s6 m4 l3"><a sl="gal_7827" href="https://www.torvaianicahotel.it/wp-content/uploads/2019/07/IMG-20181206-WA0010.jpg" class="waves-effect waves-light img gal z-depth-2"><img src="https://www.torvaianicahotel.it/wp-content/uploads/2019/07/IMG-20181206-WA0010.jpg"/></a></div></div>

Content retrieved from post body:

<div class="row" class="wp-block-materialize-fcd-gallery-block"><div class="col s6 m4 l3"><a sl="gal_2133" href="https://www.torvaianicahotel.it/wp-content/uploads/2019/07/IMG-20181206-WA0010.jpg" class="waves-effect waves-light img gal z-depth-2"><img src="https://www.torvaianicahotel.it/wp-content/uploads/2019/07/IMG-20181206-WA0010.jpg"/></a></div></div>

两者之间的唯一区别是不同的随机数,因此似乎lightbox属性没有保存,并且每次都将其实例化为默认值...?知道为什么会这样吗?

编辑:

好像我设法通过将默认值设置为null并在编辑时检查它是否为null,然后将属性设置为随机值(如果它为null ...)来修复它...

我不知道为什么这样做,所以如果有人可以解释我,我仍然会对适当的解释感兴趣。 (这就是为什么我没有回答自己的原因)

javascript wordpress wordpress-gutenberg
1个回答
0
投票

这就是您的块遇到错误的原因:

基于已渲染的save输出检查块验证。当您加载块编辑器并且重新生成的save输出标记不变时,则没有错误。

在您的情况下,由于您总是会随机生成一个属性,因此渲染的save输出也会每次更改。因此,每次您运行save函数时,总会得到唯一的标记,并使该块无效。

通过将属性的默认值更改为null,然后仅在属性值为null时才生成唯一ID,可以防止以后的加载重新生成该值并使该块无效。

而且,每个块都有一个名为clientId的属性,该属性已经是一个随机的唯一ID,因此使用它而不是生成自己的ID也可能是个好主意。

© www.soinside.com 2019 - 2024. All rights reserved.