我正在使用React构建一个使用Wordpress作为后端的网站的前端。特别是,我正在使用Wordpress REST API拉入并显示内容。
默认情况下,Wordpress REST API不会公开菜单信息,因此我对其进行了扩展,将其包括在内:
function get_menu( $data ) {
return wp_get_nav_menu_items( $data[ \'slug\' ] );
}
add_action( \'rest_api_init\', function () {
register_rest_route( \'custom\', \'/menus/(?P<slug>[a-zA-Z0-9-]+)\',
array(
\'methods\' => \'GET\',
\'callback\' => \'get_menu\'
)
);
});
现在,我可以通过以下请求访问菜单信息:
http://localhost:8888/learn-react/admin/wp-json/custom/menus/main-menu
我对菜单中包含的每个项目的响应如下所示:
ID: 13
attr_title: ""
classes: [""]
comment_count: "0"
comment_status: "closed"
db_id: 13
description: ""
filter: "raw"
guid: "http://localhost:8888/learn-react/admin/?p=13"
menu_item_parent: "0"
menu_order: 3
object: "page"
object_id: "8"
ping_status: "closed"
pinged: ""
post_author: "1"
post_content: " "
post_content_filtered: ""
post_date: "2018-02-10 08:57:52"
post_date_gmt: "2018-02-10 08:57:52"
post_excerpt: ""
post_mime_type: ""
post_modified: "2018-02-10 08:57:52"
post_modified_gmt: "2018-02-10 08:57:52"
post_name: "13"
post_parent: 0
post_password: ""
post_status: "publish"
post_title: ""
post_type: "nav_menu_item"
target: ""
title: "About"
to_ping: ""
type: "post_type"
type_label: "Page"
url: "http://localhost:8888/learn-react/admin/about/"
xfn: ""
我的问题是,我试图使用这些数据在每个菜单项上放置一个链接,但由于我使用的是React Router,所以我不需要整个url(上面的数据中提供),只需要最后的slug。这是我的菜单组件:
class MainMenu extends React.Component {
componentDidMount() {
this.props.fetchMainMenu();
}
render() {
let menuItemsArray = store.getState().menuReducer.mainMenuItems;
let menuItems = menuItemsArray.map( ( menuItem, index ) => {
return(
<li key={ index }>
<Link to={ menuItem.url }>{ menuItem.title }</Link>
</li>
)
})
return (
<ul>{ menuItems }</ul>
)
}
}
使用
menuItem.url
当然,生成以下href:
http://localhost:3000/http://localhost:8888/learn-react/admin/about/
正如我所说,我需要
menuItem.slug
要生成:
http://localhost:3000/learn-react/admin/about/
我有什么选择?