我现在正在摆弄古腾堡,我一直在尝试建立一个动态的区块。这是我正在使用的代码(为了清晰起见,省略了一些代码):
registerBlockType( \'my/block\', {
title: __( \'My Block\' ),
icon: \'email\',
category: \'common\',
attributes: {
menu: {
type: \'string\',
default: \'\',
},
},
edit: withAPIData( ( props ) => {
return {
menu_selected: `/menus/v1/menus/${ props.attributes.menu }` // custom endpoint
};
} ) ( ( props ) => {
const attributes = props.attributes;
const menu_selected = props.menu_selected.data;
const setMenu = value => {
props.setAttributes( { menu: value } );
};
console.log( JSON.stringify( menu_selected ) );
const ar = menu_selected.map( ( item ) => {
return (
<li className="menu_item">
{ item.post_title }
</li>
);
} );
}
} );
console.log( JSON.stringify( menu_selected ) )
返回以下字符串:
[{"ID":3729,"post_title":"Item 1","post_type":"nav_menu_item"},
{"ID":3730,"post_title":"Item 2","post_type":"nav_menu_item"}]
但是当我打电话的时候
map()
在
menu_selected
var我得到一个“menu\\u selected is undefined”错误,我不明白为什么。
有什么想法吗?
提前感谢
最合适的回答,由SO网友:David Sword 整理而成
我想你必须通过menu_selected
edit: withAPIData( ( props ) => {
return {
menu_selected: `/menus/v1/menus/${ props.attributes.menu }` // custom endpoint
};
} ) ( ( { menu_selected } ) => {
我能做一件非常类似的事情,就像这样:
edit: withAPIData( () => {
return {
posts: \'/wp/v2/images?per_page=4&_embed\'
};
} )( ( { posts, className } ) => {
if ( ! posts.data ) {
return "loading !";
}
if ( posts.data.length === 0 ) {
return "No posts";
}