gpt4 book ai didi

javascript - 正确使用 wp.data.subscribe

转载 作者:行者123 更新时间:2023-12-04 18:36:20 29 4
gpt4 key购买 nike

使用方法wp.data.subscribe为了显示/隐藏特定帖子格式(音频,视频和画廊)的 block ,我测试了此代码,并且在编写帖子内容时触发了该代码,并且在选择其他任何选项时触发了,因此在编写时,目标 block 闪烁。

wp.data.subscribe(() => {

var postFormat = wp.data.select('core/editor').getEditedPostAttribute('format');


$('#blockAudio, #blockVideo, #blockGallery').hide();


if( postFormat == 'gallery' ) {

$('#blockGallery').fadeIn();

}

});

最佳答案

wp.data.subscribe是 Redux 的 store.subscribe 的包装器.
来自 Redux 文档:

subscribe(listener) adds a change listener. It will be called any time an action isdispatched, and some part of the state tree may potentially havechanged. You may then call getState() to read the current state treeinside the callback.


我的解释: wp.data.subscribe根据设计,每次当前状态发生变化时都会调用它。在编辑器中编辑帖子时,状态会更改无数次,因此每次调用监听器函数是有意义的。我敢打赌,如果状态的相关部分发生了变化,你应该检查自己,然后做你想做的事情。
所以我认为你可以像这样修改你的代码:
const getPostFormat = () => wp.data.select('core/editor').getEditedPostAttribute('format');

// set the initial postFormat
let postFormat = getPostFormat();

wp.data.subscribe(() => {

// get the current postFormat
const newPostFormat = getPostFormat();

// only do something if postFormat has changed.
if( postFormat !== newPostFormat ) {

// Do whatever you want after postFormat has changed
if (newPostFormat == 'gallery') {
$('#blockAudio, #blockVideo, #blockGallery').hide();
$('#blockGallery').fadeIn();
}

}

// update the postFormat variable.
postFormat = newPostFormat;

});
资料来源:
  • https://redux.js.org/api/store/#subscribelistener
  • https://developer.wordpress.org/block-editor/packages/packages-data/#generic-stores
  • 关于javascript - 正确使用 wp.data.subscribe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301472/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com