块编辑器开发文档

@wordpress/views

💡 云策文档标注

概述

@wordpress/views 是一个轻量级包,用于通过 WordPress 偏好设置管理 DataViews 视图状态并实现持久化。它提供自动保存和恢复、视图修改检测、重置功能,并作为手动状态管理的即插即用替代方案。

关键要点

  • 持久化:使用 @wordpress/preferences 自动保存和恢复 DataViews 状态
  • 视图修改检测:跟踪视图是否与默认状态不同
  • 重置功能:提供简单重置到默认视图的能力
  • 集成简便:可作为手动视图状态管理的直接替换
  • 安装:通过 npm install @wordpress/views --save 安装
  • 核心 API:包括 loadView、useView 和 useViewConfig 函数和钩子

代码示例

// 使用 loadView 异步加载视图状态
const view = await loadView({
  kind: 'postType',
  name: 'post',
  slug: 'list',
  defaultView: { layout: 'grid' },
  activeViewOverrides: { sort: 'date' },
  queryParams: { page: 1, search: 'example' }
});

// 使用 useView 钩子管理视图状态
const { view, isModified, updateView } = useView(config);

// 使用 useViewConfig 钩子获取实体视图配置
const config = useViewConfig({ kind: 'taxonomy', name: 'category' });

注意事项

  • loadView 是异步函数,适用于路由加载器
  • useView 钩子提供本地持久化,返回当前视图、修改状态和更新函数
  • useViewConfig 钩子从核心数据存储中检索实体配置,返回 default_view、default_layouts 和 view_list
  • 配置参数如 kind、name、slug 需根据具体实体类型设置

📄 原文内容

A lightweight package for managing DataViews view state with persistence using WordPress preferences.

The @wordpress/views package provides:

  • Persistence: Automatically saves and restores DataViews state using @wordpress/preferences
  • View Modification Detection: Tracks when views differ from their default state
  • Reset Functionality: Simple reset to default view capability
  • Clean Integration: Drop-in replacement for manual view state management

Installation

Install the module

npm install @wordpress/views --save

API Reference

loadView

Async function for loading view state in route loaders.

Parameters

  • config ViewConfig: Configuration object for loading the view.
  • config.kind ViewConfig: Entity kind (e.g., ‘postType’, ‘taxonomy’, ‘root’).
  • config.name ViewConfig: Specific entity name.
  • config.slug ViewConfig: View identifier.
  • config.defaultView ViewConfig: Default view configuration.
  • config.activeViewOverrides ViewConfig: View overrides applied on top but never persisted.
  • config.queryParams ViewConfig: Object with page and/or search from URL.

Returns

  • Promise resolving to the loaded view object.

useView

Hook for managing DataViews view state with local persistence.

Parameters

  • config ViewConfig: Configuration object for loading the view.

Returns

  • UseViewReturn: Object with current view, modification state, and update functions.

useViewConfig

A hook that retrieves the view configuration for a given entity from the core data store.

Parameters

  • params Object:
  • params.kind string: The kind of the entity.
  • params.name string: The name of the entity.

Returns

  • Object: An object containing the default_view, default_layouts, and view_list configuration for the entity.