微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何触发块的重新渲染?

如何解决如何触发块的重新渲染?

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 来显示块的内容(例如段落块),该内容会在编辑器上自动更新,但不会立即更新。只有当我的光标离开该块时,或者当我将输入焦点移出该块时,才会重新渲染该块。

我可以在上面的代码添加什么来强制编辑器在 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 中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。