Javascript Wordpress块:registerBlockType编辑函数中的异步REST调用
我正在编写一个WordPress插件来创建一个块,该块需要使用一个自定义REST端点来提取数据,在下面的示例中,该端点返回一个简单的字符串。我想在registerBlockType配置的edit()和save()返回中包含此字符串。我使用fetch()调用REST端点,但这显然是异步的。如果您有任何关于最佳方式的想法,我们将不胜感激,谢谢:Javascript Wordpress块:registerBlockType编辑函数中的异步REST调用,javascript,wordpress,rest,asynchronous,wordpress-gutenberg,Javascript,Wordpress,Rest,Asynchronous,Wordpress Gutenberg,我正在编写一个WordPress插件来创建一个块,该块需要使用一个自定义REST端点来提取数据,在下面的示例中,该端点返回一个简单的字符串。我想在registerBlockType配置的edit()和save()返回中包含此字符串。我使用fetch()调用REST端点,但这显然是异步的。如果您有任何关于最佳方式的想法,我们将不胜感激,谢谢: const { registerBlockType } = wp.blocks registerBlockType( 'daisy-views/da-t
const { registerBlockType } = wp.blocks
registerBlockType( 'daisy-views/da-test', {
title: 'Daisy Test: Test Block',
icon: 'format-gallery',
category: 'common',
attributes: {
gid: {
default: 2,
type: 'integer'
},
},
edit( props ) {
const restEP = daRestUrl + 'test'
fetch( restEP, {
body: JSON.stringify( {p: 'test param'}), // test parameters
cache: 'no-cache',
method: 'POST',
redirect: 'follow',
referrer: 'no-referrer',
headers : {
'Access-Control-Allow-Origin' : '*',
'X-WP-Nonce' : wpApiSettings.nonce,
}
})
.then( response => {
response.json()
.then( data => {
var returnValue = data.data // REST test, returns a string
console.log( 'Fetch returns: ', returnValue )
})
})
return <div>
test block edit
{/* return value from fetch here */}
</div>
},
save( props ) {
return <div>
Test Block
{/* return value from fetch here */}
</div>
}
} );
const{registerBlockType}=wp.blocks
registerBlockType('菊花视图/da测试'{
标题:“雏菊试验:试块”,
图标:“格式库”,
类别:'普通',
属性:{
基德:{
默认值:2,
类型:“整数”
},
},
编辑(道具){
const restEP=daRestUrl+“测试”
取回{
body:JSON.stringify({p:'test param'}),//测试参数
缓存:“无缓存”,
方法:“POST”,
重定向:“跟随”,
推荐人:“无推荐人”,
标题:{
“访问控制允许来源”:“*”,
“X-WP-Nonce”:wpApiSettings.Nonce,
}
})
。然后(响应=>{
response.json()
。然后(数据=>{
var returnValue=data.data//REST测试,返回字符串
log('Fetch returns:',returnValue)
})
})
返回
试块编辑
{/*从此处获取返回值*/}
},
保存(道具){
返回
试块
{/*从此处获取返回值*/}
}
} );
到目前为止,我最好的解决方案是添加一个code属性,并让fetch调用用HTML填充该属性。如果在编辑函数中直接调用fetch,则需要进行检查,以防止在更新属性时在无休止的循环中调用fetch