我得到一个Promise
当我执行console.log( mypost )
是的,因为apiFetch()
确实返回了Promise
对象,以及apiFetch()
不会将从服务器收到的响应分配给mypost
常量,以及then()
回调也不会分配给mypost
变量
如何获取post对象?
As suggested by React, 您需要添加mypost
作为组件中的本地状态,然后发出XHR/AJAX请求(使用apiFetch()
, 本地人window.fetch()
, Axios或其他)中的componentDidMount()
类组件的方法,或使用useEffect
hook 在功能组件中。
示例使用apiFetch()
具有useEffect
:
import { useState, useEffect } from \'@wordpress/element\';
import apiFetch from \'@wordpress/api-fetch\';
function MyComponent( { post_id } ) {
const [ error, setError ] = useState( null );
const [ mypost, setPost ] = useState( null );
const [ isLoaded, setIsLoaded ] = useState( false );
useEffect( () => {
apiFetch( { path: `custombase/v1/post/${ post_id }` } ).then(
( result ) => {
setIsLoaded( true );
setPost( result );
},
( error ) => {
setIsLoaded( true );
setError( error );
}
);
}, [ post_id ] );
if ( error ) {
return <p>ERROR: { error.message }</p>;
} else if ( ! isLoaded ) {
return <p>Loading post { post_id }..</p>;
} else if ( mypost && mypost.id ) {
return <h3>Post <i>{ mypost.title || \'#\' + mypost.id }</i> loaded!</h3>;
}
return <p>No such post</p>;
}
// Sample usage: <MyComponent post_id="1239" />
替代解决方案:将自定义端点的实体添加到块编辑器中的实体列表中使用添加实体addEntities()
:
import { dispatch } from \'@wordpress/data\';
dispatch( \'core\' ).addEntities( [{
baseURL: \'/custombase/v1/post\',
// The \'post\' is not a post type - it\'s the "post" as in /post above. Also, "kind"
// and "name" are not documented, so let\'s assume they form the above baseURL..
kind: \'custombase/v1\',
name: \'post\',
label: \'Post or whatever\',
}] );
// You can, for example, call the above (i.e. add the entity) before you register your
// block type.
然后使用
getEntityRecord()
要从终结点获取post数据,请执行以下操作:
const mypost = select( \'core\' ).getEntityRecord( \'custombase/v1\', \'post\', 1239 );
// Note that getEntityRecord() caches the results.
请注意
getEntityRecord()
要正常工作,端点回调必须使用小写
id
而不是
ID
:
// In the get_post_rest() function:
$data = array(
\'id\' => $post->ID, // use id and *not* ID
\'title\' => $post->post_title,
);
例如,使用
useSelect
, 上述组件(
MyComponent
) 现在看起来是这样的:
import { useSelect } from \'@wordpress/data\';
function MyComponent( { post_id } ) {
const { mypost, isLoading } = useSelect( ( select ) => {
const args = [ \'custombase/v1\', \'post\', post_id ];
return {
mypost: select( \'core\' ).getEntityRecord( ...args ),
isLoading: select( \'core/data\' ).isResolving( \'core\', \'getEntityRecord\', args )
};
}, [ post_id ] );
if ( isLoading ) {
return <p>Loading post { post_id }..</p>;
} else if ( mypost && mypost.id ) {
return <h3>Post <i>{ mypost.title || \'#\' + mypost.id }</i> loaded!</h3>;
}
return <p>No such post</p>;
}