多个呼叫是否可以在一个内部组合useSelect选择器?
是的,这里有一个例子useSelect() 返回使用destructuring赋值解包的对象(例如。const { a, b } = myFunc() 哪里myFunc() 退货{ a: \'foo\', b: 123 }):
const { groups, selectedGroup, faqs } = useSelect( ( select ) => {
const { getEntityRecords } = select( \'core\' );
// The args are identical for both "groups" and selectedGroup, so I put them in a constant.
const groupsArgs = { per_page: -1, orderby: \'name\', order: \'asc\', _fields: \'id,name,slug\' };
const selectedGroup = getEntityRecords( \'taxonomy\', \'faq_group\', groupsArgs )?.find(
( term ) => term.slug === attributes.group
);
return {
groups: getEntityRecords( \'taxonomy\', \'faq_group\', groupsArgs ),
faqs: getEntityRecords( \'postType\', \'faq\', { faq_group: [ selectedGroup?.id ] } ),
selectedGroup,
};
}, [ attributes.group ] );
如果您实际上不需要访问
selectedGroup 从外部
useSelect() 回调,则可以忽略
selectedGroup 从列表中,即仅使用
const { groups, faqs } = useSelect( ... ), 然后移除
selectedGroup, (第三行)返回值。
实际上,不是打电话getEntityRecords() 使用相同的参数两次,可以只调用一次:
const { groups, selectedGroup, faqs } = useSelect( ( select ) => {
const { getEntityRecords } = select( \'core\' );
const groupsArgs = { per_page: -1, orderby: \'name\', order: \'asc\', _fields: \'id,name,slug\' };
const groups = getEntityRecords( \'taxonomy\', \'faq_group\', groupsArgs );
const selectedGroup = groups?.find( ( term ) => term.slug === attributes.group );
return {
groups,
selectedGroup,
faqs: getEntityRecords( \'postType\', \'faq\', { faq_group: [ selectedGroup?.id ] } ),
};
}, [ attributes.group ] );