商店通知商店 (wc/store/store-notices)
概述
商店通知商店允许注册和注销通知容器。这对于在特定位置(例如自定义区块)显示通知非常有用。
用法
要使用此商店,您需要在任何引用它的模块中汇入 storeNoticesStore 的 StoreDescriptor。假设 @woocommerce/block-data 已注册为指向 wc.wcBlocksData 的外部依赖,您可以通过以下方式汇入 StoreDescriptor:
import { storeNoticesStore } from '@woocommerce/block-data';
如果未注册,则从 window 对象访问它,如下所示:
const { storeNoticesStore } = window.wc.wcBlocksData;
示例
以下代码片段演示了如何为通知注册容器。
import { store as noticesStore } from '@wordpress/notices';
export default function Block( attributes ) {
const context = 'your-namespace/custom-form-step';
dispatch( noticesStore ).createNotice(
'error',
'This is an example of an error notice.',
{ context }
);
return (
<>
<StoreNoticesContainer context={ context } />
{ /* 你的自定义区块代码放在这里 */ }
</>
);
}
💡 在内部,
StoreNoticesContainer组件将派发registerContainer操作。
请注意,这是一个简单的示例。在实践中,你可能会希望在响应用户操作(例如提交表单)时触发 createNotice 操作。
操作
registerContainer( containerContext )
此操作将注册一个新的容器。
参数
- containerContext
string: 要注册的容器的上下文或标识符。
返回
object: 一个包含以下属性的操作对象:- type
string: 操作的类型。 - containerContext
string: 通过的 containerContext。
- type
例子
import { storeNoticesStore } from '@woocommerce/block-data';
dispatch( storeNoticesStore ).registerContainer( 'someContainerContext' );
unregisterContainer( containerContext )
此操作将注销一个现有的容器。
参数
- containerContext
string: 要取消注册的容器的上下文或标识符。
返回值
object: 一个包含以下属性的操作对象:- type
string: 操作的类型。 - containerContext
string: 通过的 containerContext。
- type
例子
import { storeNoticesStore } from '@woocommerce/block-data';
dispatch( storeNoticesStore ).unregisterContainer( 'someContainerContext' );
选择器
getRegisteredContainers
从状态中返回当前已注册容器的列表。
返回值
string[]: 一个包含已注册容器上下文的字符串数组。
例子
import { storeNoticesStore } from '@woocommerce/block-data';
const store = select( storeNoticesStore );
const registeredContainers = store.getRegisteredContainers();