繁体   English   中英

如何触发块的重新渲染?

[英]How do I trigger a re-rendering of a block?

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 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 );

对于上述代码,我的插件将 props.attributes.content 发送到外部 API,并异步更新。 在视觉上,由于许多默认的古腾堡块使用 props.attributes.content 来显示块的内容(例如段落块),该内容会在编辑器上自动更新,但不会立即更新。 仅当我的 cursor 离开块时,或者当我将输入焦点移出该块时,才会重新渲染块。

一旦 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 );

尽管如此,在输入一个块时,在您的 api 响应之前可能会有一点延迟。 此外,也许您需要将 BlockEdit 包装在 HigherOrderComponent 中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM