块编辑器开发文档

💡 云策文档标注

概述

本文档介绍了 WordPress 核心 preferences 命名空间,用于管理用户偏好的状态和操作。它提供了选择器和动作来获取、设置、切换偏好,并支持持久化层配置。

关键要点

  • 命名空间为 core/preferences,用于处理偏好相关功能。
  • 选择器 get 用于检查特定范围内偏好是否激活,参数包括 state、scope 和 name。
  • 动作包括 set(设置偏好值)、setDefaults(设置偏好默认值)、setPersistenceLayer(配置持久化层)和 toggle(切换偏好状态)。
  • setPersistenceLayer 应在应用生命周期早期调用,以启用偏好持久化。

代码示例

// 示例:使用 get 选择器检查偏好
const isEnabled = get(state, 'core/edit-post', 'featureName');

// 示例:使用 set 动作设置偏好
dispatch(set('core/edit-post', 'preferenceName', true));

// 示例:使用 setPersistenceLayer 配置持久化层
dispatch(setPersistenceLayer(persistenceLayer));

注意事项

  • setPersistenceLayer 应在其他动作之前调用,以确保偏好状态正确初始化。
  • 偏好值可以是任意类型,具体取决于应用需求。

📄 原文内容

Namespace: core/preferences.

Selectors

get

Returns a boolean indicating whether a prefer is active for a particular scope.

Parameters

  • state StoreState: The store state.
  • scope string: The scope of the feature (e.g. core/edit-post).
  • name string: The name of the feature.

Returns

  • *: Is the feature enabled?

Actions

set

Returns an action object used in signalling that a preference should be set to a value

Parameters

  • scope string: The preference scope (e.g. core/edit-post).
  • name string: The preference name.
  • value *: The value to set.

Returns

  • SetAction: Action object.

setDefaults

Returns an action object used in signalling that preference defaults should be set.

Parameters

  • scope string: The preference scope (e.g. core/edit-post).
  • defaults ScopedDefaults: A key/value map of preference names to values.

Returns

  • SetDefaultsAction: Action object.

setPersistenceLayer

Sets the persistence layer.

When a persistence layer is set, the preferences store will:

  • call get immediately and update the store state to the value returned.
  • call set with all preferences whenever a preference changes value.

setPersistenceLayer should ideally be dispatched at the start of an application’s lifecycle, before any other actions have been dispatched to the preferences store.

Parameters

  • persistenceLayer WPPreferencesPersistenceLayer< D >: The persistence layer.

Returns

  • Promise< SetPersistenceLayerAction< D > >: Action object.

toggle

Returns an action object used in signalling that a preference should be toggled.

Parameters

  • scope string: The preference scope (e.g. core/edit-post).
  • name string: The preference name.