You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress Gutenberg自定义display-mobile-advertising块中advertisers数组map函数无法执行问题求助

问题排查与解决方案

我帮你梳理了代码里的几个核心问题,正是这些问题导致advertisers数组无法执行map函数,进而无法渲染条目:

问题1:advertisers属性未设置初始值

你在attributes里定义了advertisers为数组类型,但没有指定默认值,所以它的初始值是undefined。而undefined是没有map方法的,这直接导致了渲染时报错。

问题2:addNewItem函数中错误访问属性

在addNewItem里你直接用了attributes.advertisers,但实际上attributes是包含在props参数里的,应该写成props.attributes.advertisers,否则会找不到这个变量。

问题3:输入框事件处理函数拼写错误

输入框的onChane是拼写错误,正确的应该是onChange,这会导致你输入的内容无法更新inputData属性,点击添加按钮时会把空值或者旧值推入数组。

问题4:save函数未正确渲染内容

当前save函数返回null,这会导致前端页面(非编辑器界面)无法看到已添加的条目,需要把列表渲染逻辑加进去。


修复后的完整代码

/**
 * BLOCK: display-mobile-advertising
 *
 * Registering a basic block with Gutenberg.
 * Simple block, renders and saves the same content without any interactivity.
 */
// Import CSS.
import { TextareaControl } from '@wordpress/components';
import { useState } from '@wordpress/element';
import './editor.scss';
import './style.scss';

const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks

/**
 * Register: aa Gutenberg Block.
 *
 * Registers a new block provided a unique name and an object defining its
 * behavior. Once registered, the block is made editor as an option to any
 * editor interface where blocks are implemented.
 *
 * @param {string} name Block name.
 * @param {Object} settings Block settings.
 * @return {?WPBlock} The block, if it has been successfully
 * registered; otherwise `undefined`.
 */
registerBlockType( 'cgb/block-display-mobile-advertising', {
	// Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
	title: __( 'display-mobile-advertising - CGB Block' ), // Block title.
	icon: 'shield', // Block icon from Dashicons.
	category: 'common', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
	keywords: [
		__( 'display-mobile-advertising — CGB Block' ),
		__( 'CGB Example' ),
		__( 'create-guten-block' ),
	],

	attributes: {
		inputData: {
			type: 'string',
			default: '' // 给inputData加上默认空字符串,避免初始值为undefined
		},
		advertisers: {
			type: 'array',
			default: [] // 关键:给数组设置初始空数组
		}
	},
	edit: ( props ) => {
		const { attributes, setAttributes } = props; // 解构props,代码更简洁

		function updateData(event){
			setAttributes({ inputData: event.target.value })
		}

		function addNewItem () {
			// 先判断inputData是否为空,避免添加空条目
			if (!attributes.inputData.trim()) return;

			// 从props.attributes里获取数组,然后创建新数组
			const updatedAdvertisers = [...attributes.advertisers, attributes.inputData];
			setAttributes({ 
				advertisers: updatedAdvertisers,
				inputData: "" // 清空输入框
			});
		};

		return (
			<div>
				<label>Write your text here</label>
				<input 
					type="text" 
					value={ attributes.inputData } 
					onChange={ updateData } // 修复拼写错误
				/>
				<button onClick={ addNewItem }>Add Item</button>
				<ul>
					{ attributes.advertisers.map((advertiser, index) => (
						<li key={ index }>{ advertiser }</li> // 加上key属性,符合React渲染要求
					)) }
				</ul>
			</div>
		);
	},

	save: ( props ) => {
		const { attributes } = props;
		return (
			<div>
				<ul>
					{ attributes.advertisers.map((advertiser, index) => (
						<li key={ index }>{ advertiser }</li>
					)) }
				</ul>
			</div>
		);
	},
} );

额外优化点说明

  • 给inputData加上默认空字符串,避免初始值为undefined;
  • 在addNewItem里增加了空值判断,防止用户添加空条目;
  • 解构了props里的attributes和setAttributes,让代码更简洁易读;
  • 给列表项添加了key属性,避免React控制台警告。

内容的提问来源于stack exchange,提问作者Nika Zerekidze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 21:02:26