我没有任何开发 wordpress 插件的经验,我想在古腾堡编辑器中创建一个滑块插件,该插件应根据所选类别显示博客文章。因此,我必须在提供所有类别列表的古腾堡编辑器中创建一个选择框或类似的东西。我尝试了多种想法来完成这项工作,但不幸的是我失败了。我认为我的问题是 apiFetch 函数的异步请求。 例如,我尝试了以下操作:
const getPosts = function ()
{
console.log('sadsadsadsad'); //todo remove debug
let options = [];
return wp.apiFetch( { path: '/wp/v2/posts' } ).then( function( posts ){
for (let i = 0; i < posts.length; i++) {
option = el(
'option',
{ value: posts[i].id },
posts[i].title.raw
);
options.push(option);
}
return options;
})
}
内部
<块引用>编辑:(道具)=> {
return [
el(
SelectControl,
{
options: getPosts(),
}
)
]
由于异步加载,这无法工作。当我用谷歌搜索另一个解决方案时,我想出了以下代码片段:
function cheat() {
this.cheat = this;
this.types = [];
let that = this;
this.get_posts = function () {
return new Promise(
function ( resolve ) {
wp.apiFetch( { path : '/wp/v2/types' } ).then(
function ( types ) {
that.types = types;
},
wp.apiFetch( { path: '/wp/v2/posts' } ).then(
function ( res ) {
resolve( res )
}
)
)
}
)
};
this.post_selector_opts = function () {
let cheat = this.cheat;
return new Promise(
function ( resolve ) {
cheat.get_posts()
.then(
function ( posts ) {
let opts = [{ key: 'none', label: 'Select Post', value: 0 }];
for ( const P of posts ) {
opts.push( { key: P.slug, label: P.title, value: P.id } );
}
resolve( opts );
}
)
}
)
};
this.init = function () {
this.post_selector_opts().then( opts => {
cheater.posts = opts;
} )
}
}
const cheater = { posts: [] };
let shared = new cheat();
shared.init();
内部
<块引用>编辑:(道具)=> {
return [
el(
SelectControl,
{
options: cheater.posts,
}
)
]
因此我收到错误
<块引用>错误:缩小反应错误 #31;访问 https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7Brendered%7D&args[]= 获取完整消息,或使用非缩小开发环境获取完整错误和其他有用警告。
但是如果我尝试使用
构建开发版本 <块引用>npm run build --dev --configuration=dev
它仍然生成一个缩小的生产版本。 你能帮我编码一个包含我的类别的选择框吗?你有什么建议吗?