如何使用 Gutenberg withSelect 重新渲染 .map() 列表内部
我正在创建古腾堡自定义块内容表,该块反应性地反映 h2 文本。 在map()之外,它可以工作。但里面不工作。
请让我知道如何修改此代码。
谢谢。
import { registerBlockType } from "@wordpress/blocks";
import { withSelect, select } from "@wordpress/data";
registerBlockType("theme/toc", {
title: "TOC",
icon: "list-view",
category: "layout",
edit: withSelect((select) => {
return {
blocks: select("core/block-editor").getBlocks(),
};
})(Edit),
save: () => {
return null;
},
});
export function Edit(props) {
const { blocks = [] } = props;
const headings = [];
blocks.forEach((el) => {
if (!(el.name === "core/heading" && el.attributes.level === 2)) {
return;
}
headings.push(el.attributes.content);
});
return (
<div>
<p>{headings[0]}</p> // this line works
<ol>
{headings.map((h2, i) => { // not working
<li key={i}>
<a>{h2}</a>
</li>;
})}
</ol>
</div>
);
}
I'm creating table of content Gutenberg custom block which reactive reflect h2 text.
Outside of map(), it works. but inside not working.
Please let me know how to modify this code.
thanks.
import { registerBlockType } from "@wordpress/blocks";
import { withSelect, select } from "@wordpress/data";
registerBlockType("theme/toc", {
title: "TOC",
icon: "list-view",
category: "layout",
edit: withSelect((select) => {
return {
blocks: select("core/block-editor").getBlocks(),
};
})(Edit),
save: () => {
return null;
},
});
export function Edit(props) {
const { blocks = [] } = props;
const headings = [];
blocks.forEach((el) => {
if (!(el.name === "core/heading" && el.attributes.level === 2)) {
return;
}
headings.push(el.attributes.content);
});
return (
<div>
<p>{headings[0]}</p> // this line works
<ol>
{headings.map((h2, i) => { // not working
<li key={i}>
<a>{h2}</a>
</li>;
})}
</ol>
</div>
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需卸下卷曲括号,以便可以从地图功能返回JSXELEMNT。
要注意的其他事情是,不建议将元素索引
i
用作键
值。您可能需要使用您要通过的元素中的ID等更独特的值。Simply remove the curly braces so the JSXElemnt can be returned from the map function.
something else to note is it's not advised to use the element index
i
as thekey
value. you may want to use a more unique value like id from the element you're looping through.