我想用fetch
从速率受限的第三方API获取信息。我尝试使用的不是前端的APIfetch
在edit函数中执行API调用。我似乎已经让fetch工作了,但似乎无法保存数据。有人能告诉我哪里出了问题吗?
属性如下所示:
attributes: {
url: {
type: \'string\',
selector: \'.o_microlink\',
attribute: \'href\',
default: \'\',
},
title: {
type: \'string\',
selector: \'.o_microlink\',
default: \'\',
},
}
编辑功能如下所示:edit: props => {
const onChangeURL = async value => {
const response = await fetch( `https://api.microlink.io?url=${ value }`, {
cache: \'no-cache\',
headers: {
\'user-agent\': \'WP Block\',
\'content-type\': \'application/json\'
},
method: \'GET\',
redirect: \'follow\',
referrer: \'no-referrer\',
}).then(
returned => {
if (returned.ok) return returned;
throw new Error(\'Network response was not ok.\');
}
);
let data = await response.json();
data = data.data;
props.setAttributes( { url: value } );
props.setAttributes( { title: data.title} );
};
return <div className={ props.className }>
<RichText
tagName="div"
placeholder={ __( \'Add URL here.\' ) }
value={ props.attributes.url }
onChange={ onChangeURL }
/>
{ ! props.attributes.title ? __( \'Add URL\' ) : <div> { props.attributes.title } </div> }
</div>;
}
保存功能非常标准:save: props => {
return (
<div className={ [props.className, \'o_microlink\'].join( \' \' ) }>
<a href={ props.url}> { props.title } </a>
</div>
);
}