在我正在开发的Gutenberg组件中,我有一个函数,可以在常量中指定的多个帖子类型中搜索关键字:
const postTypes = [ \'posts\', \'pages\', \'portfolio\' ];
const onSearchStringChange = ( keyword ) => {
Promise.all( postTypes.map( postType => apiFetch( {
path: `/wp/v2/${ postType }?search=${ keyword }`,
} ) ) ).then( ( results ) => {
console.log( results.reduce( ( result, final ) => [...final, ...result], [] ) );
} )
};
该函数按预期工作并返回一个结果数组。
我希望获得可查看的帖子类型(减去attachment
post type)通过函数访问站点。这就是我正在使用的:
const postTypes = useSelect( ( select ) => {
const { getPostTypes } = select( \'core\' );
const excludedPostTypes = [ \'attachment\' ];
const filteredPostTypes = getPostTypes( { per_page: -1 } )?.filter(
( { viewable, slug } ) => viewable && ! excludedPostTypes.includes( slug )
);
const result = ( filteredPostTypes || [] ).map( ( { slug } ) => slug );
return result;
}, [] );
该函数也按预期工作,我得到了一个所有可查看帖子类型的slug数组
attachment
.
但是,如果我将结果数组传递给onSearchStringChange
函数我收到以下错误:
Uncaught (in promise)
Object { code: "rest_no_route", message: "No route was found matching the URL and request method.", data: {…} }
code: "rest_no_route"
data: Object { status: 404 }
message: "No route was found matching the URL and request method."
<prototype>: Object { … }
我假设在调用
onSearchStringChange
作用即使我做了
postTypes.length > 0
在
apiFetch
我也有同样的错误。
所以,我的问题是:在调用时,如何确保post-types数组被完全解析onSearchStringChange
?