我有一个自定义gutenberg块,它在编辑时通过wp json动态获取自定义post数据。如何为前台保存数据?
这是我的自定义组件(preview.js) 我在编辑方法中包括
const { __ } = wp.i18n
const { Component } = wp.element
export default class Preview extends Component {
state = {
teachers: false,
}
getTeachers = () => {
const { location } = this.props.attributes
fetch( `/wp-json/wp/v2/teachers` )
.then( response => response.json() )
.then( teachers => {
this.setState( { teachers: teachers } )
} )
}
componentWillMount() {
this.getTeachers()
}
componentDidUpdate(lastProps, lastStates) {
if( lastProps.attributes.productID != this.props.attributes.productID ) {
this.getTeachers()
}
}
render() {
const { teachers } = this.state
let wrapper;
if (teachers) {
wrapper = teachers.map(function (teacher) {
return (
<div className="wp-block-profiles__element" key={teacher.id}>
<div className="wp-block-profiles__image-container">
<img className="wp-block-profiles__image" src={ teacher.profile_image.url } alt={ teacher.profile_image.alt } />
</div>
<h4>{teacher.first_name} {teacher.last_name}</h4>
</div>
)
})
}
return (
!! teachers ? (
<div className="wp-block-profiles">
{wrapper}
</div>
) : (
<p className="profile-block-message">{ __( \'Loading Profiles...\', \'block-profiles\' ) }</p>
)
)
}
}
这里是我注册自定义块的地方
// Import CSS.
import \'./style.scss\'
import \'./editor.scss\'
import Inspector from \'./inspect\'
import Preview from \'./preview\'
const { __ } = wp.i18n; // Import __() from wp.i18n
const {
registerBlockType,
} = wp.blocks
const { Fragment } = wp.element
/*
* @param {string} name Block name.
* @param {Object} settings Block settings.
* @return {?WPBlock} The block, if it has been successfully
* registered; otherwise `undefined`.
*/
registerBlockType( \'cgb/profiles-cgb-block\', {
// Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
title: __( \'Profiles\' ), // Block title.
icon: \'shield\', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
category: \'custom-category\', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
keywords: [
__( \'Profiles\' ),
__( \'CGB\' ),
__( \'teachers\'),
],
attributes: {
teachers: {
type: \'array\',
default: [],
},
locations: {
type: \'array\',
default: [],
},
levels: {
type: \'array\',
default: [],
}
},
edit: ( props ) => {
const { attributes, setAttributes, posts } = props
const { locations, levels, teachers } = attributes
return [
<Fragment>
<Inspector { ...{ attributes, setAttributes } } />
{ !! locations ? (
<Preview { ...{ teachers, levels, attributes } } />
) : (
<p class="profiles-block-message">{ __( \'Please select at least Location to render profiles\', \'cgb/block-profiles\' ) }</p>
) }
</Fragment>
]
},
save: ( props ) => {
return null
},
} );
在这种情况下,所有内容都保存在编辑器中,但前端没有显示任何内容