Javascript 如何触发块的重新渲染?
在WordPress Gutenberg插件中Javascript 如何触发块的重新渲染?,javascript,reactjs,asynchronous,rendering,wordpress-gutenberg,Javascript,Reactjs,Asynchronous,Rendering,Wordpress Gutenberg,在WordPress Gutenberg插件中 hooks_addFilter_editor_blockEdit = (BlockEdit) => { return (props) => { apiFetch({url: 'https://example.com/api/'+props.attributes.content }).then(_return => { props.attributes.content = _return; // What sh
hooks_addFilter_editor_blockEdit = (BlockEdit) => {
return (props) => {
apiFetch({url: 'https://example.com/api/'+props.attributes.content
}).then(_return => {
props.attributes.content = _return;
// What should I use here to force re-render the block?
})
return ( <BlockEdit { ...props } /> );
}
}
wp.hooks.addFilter( 'editor.BlockEdit', 'my-plugin-slug', hooks_addFilter_editor_blockEdit );
hooks\u addFilter\u editor\u blockEdit=(blockEdit)=>{
返回(道具)=>{
apiFetch({url:'https://example.com/api/“+props.attributes.content
})。然后(_return=>{
props.attributes.content=\u返回;
//我应该在这里使用什么来强制重新渲染块?
})
返回();
}
}
wp.hooks.addFilter('editor.BlockEdit','my plugin slug',hooks\u addFilter\u editor\u BlockEdit);
对于上面的代码,我的插件将props.attributes.content发送到外部API中,并异步更新它。视觉上,由于许多默认gutenberg块使用props.attributes.content来显示块的内容(例如段落块),该内容会在编辑器上自动更新,但不会立即更新。仅当光标离开块时,或当输入焦点离开块时,才会重新渲染块
我可以在上述代码中添加什么内容,以迫使编辑器在apiFetch调用成功后立即直观地显示更新的内容?如果这对您有效,请尝试:
hooks_addFilter_editor_blockEdit = (BlockEdit) => {
return (props) => {
// Destructure "props"
const { attributes, setAttributes } = props;
apiFetch({url: 'https://example.com/api/'+attributes.content
}).then(_return => {
// What should I use here to force re-render the block?
setAttributes( { content: _return } );
})
return ( <BlockEdit { ...props } /> );
}
}
wp.hooks.addFilter( 'editor.BlockEdit', 'my-plugin-slug', hooks_addFilter_editor_blockEdit );
hooks\u addFilter\u editor\u blockEdit=(blockEdit)=>{
返回(道具)=>{
//解构“道具”
const{attributes,setAttributes}=props;
apiFetch({url:'https://example.com/api/'+attributes.content
})。然后(_return=>{
//我应该在这里使用什么来强制重新渲染块?
setAttributes({content:_return});
})
返回();
}
}
wp.hooks.addFilter('editor.BlockEdit','my plugin slug',hooks\u addFilter\u editor\u BlockEdit);
尽管如此,在输入块时,在api响应之前可能会有一点延迟。此外,您可能需要将区块编辑包装在一个更高级的组件中。您是否成功地使其工作—除了在承诺解决后立即重新渲染?好奇的是:您是否将此限制为某些块类型(即核心/段落)?是的。除了立即重新渲染外,我对所有结果都很满意。实际上,我正在做的是马达加斯加语的拼写检查。我抓取每个块的每个文本,到目前为止,我不看块类型,而是看是使用props.attributes.content(核心/段落和其他)还是props.attributes.values(核心/列表和类似内容)。好的,我想知道是否打算在块中的每个键入上调用api,因为每次状态更改时都会调用编辑函数。可能有帮助的是:您不应该直接设置属性(不可变),还有一个额外的方法叫做“setAttributes”。我会用修改过的代码发布一个答案…谢谢,这些代码片段就像“裸骨”,让问题更容易理解。API调用实际上是排队的、缓冲的,以检查有效的更改和节流。