在Gutenberg Block中调用setAttributes()会导致编辑器模式中setState()错误



在Wordpress的编辑器模式下,当我最初渲染我的古腾堡块时,我看到React的控制台错误。对该块的任何进一步更改都不会导致此问题。

确切的错误是:"不能更新组件(EditorProvider),而呈现不同的组件(edit)。要查找edit内部错误的setState()调用,请按照堆栈跟踪"。

我原来的问题是在一个函数中,我检索Wordpress用户数据,然后将其设置为属性。但我发现它可以在一个电话中发生。例如:我在Edit返回函数中添加了导致问题的行:

setAttributes({userGravatarUrl:'http://www.gravatar.com/avatar/?d=mp'});

这是我第一次尝试在另一个组件/块的onChange属性之外使用setAttributes()。

属性名称是正确的,所以我知道这不是问题。我应该忽略这个错误吗?或者我该如何补救?

我的完整代码如下:

export default function Edit( { attributes, setAttributes } ) {
const blockProps = useBlockProps();
setAttributes({userGravatarUrl:'http://www.gravatar.com/avatar/?d=mp'});
const divStyle = {
color: attributes.textColor,
backgroundColor: attributes.backgroundColor,
};
return (
<div { ...blockProps } style={divStyle}>
<div className='block-section'>
{ attributes.displayGravatar && 
<img src = {attributes.userGravatarUrl}/>
}
</div>
</div>
);
}

block.json

"displayGravatar": {
"type": "boolean",
"default": true
},
"displayUserName":{
"type": "boolean",
"default": true
},
"displayBio":{
"type": "boolean",
"default": true
},
"selectedUserId":{
"type": "string"
},
"backgroundColor":{
"type": "string",
"default": "#FFFFFF"
},
"textColor":{
"type": "string",
"default": "#000000"
},
"userGravatarUrl":{
"type": "string"
},
"userBio":{
"type": "string"
},
"userName":{
"type": "string"
}
}```

在返回语句之前在Edit()中调用setAttributes()会导致setState()"通过在呈现另一个组件时尝试设置状态来调用。虽然这似乎是一个无害的警告,一切似乎都在工作,但许多这些糟糕的setState调用最终会导致性能下降,然后应用程序崩溃。

要在Edit()中为userGravatarUrl属性分配默认值,请更新代码以在ES6中对传入属性使用对象析构:

edit.js

export default function Edit({ attributes, setAttributes }) {
const blockProps = useBlockProps();
const {
backgroundColor,
displayGravatar,
textColor,
userGravatarUrl = "http://www.gravatar.com/avatar/?d=mp"
} = attributes;
const divStyle = {
color: textColor,
backgroundColor: backgroundColor,
};
return (
<div {...blockProps} style={divStyle}>
<div className='block-section'>
{displayGravatar &&
<img src={userGravatarUrl} />
}
</div>
</div>
);
}

对象析构也可以提高代码的可读性,因为attributes.nameOfAttribute变成了nameOfAttribute。通过避免";坏的setState()&;"今天打电话,你的明天会更轻松。

最新更新