在componentDidMount加载后重新加载渲染函数



我正在尝试加载ecwid商店在我的react.js网站。我创建了一个类组件,其中有一个名为load ecwid的函数。我把函数放在componentDidMount()中。控制台日志告诉我该功能加载得很好。但是,屏幕上什么也没有显示,除非我手动刷新页面。

下面是我的代码:

class EcwidStore extends React.Component {
state = {
isLoaded: false,
};
loadEcwid = () => {
var isEcwidPage = document.getElementById('productBrowser') != null;
if (window.ecwidLoaded && isEcwidPage) return;
window.ecwidLoaded = true;
window.ecwid_script_defer = true;
window.ecwid_dynamic_widgets = true;
window.ec.storefront = window.ec.storefront || Object();
window.ec.enable_catalog_on_one_page = true;
window._xnext_initialization_scripts = [
{
widgetType: 'ProductBrowser',
id: 'my-store-xxx',
arg: ['id=productBrowser', 'views=grid(20,3)'],
},
{
widgetType: 'CategoriesV2',
id: 'my-categories-xxx',
arg: ['id=categoriesV2'],
},
{
widgetType: 'SearchWidget',
id: 'my-search-xxx',
arg: ['id=searchWidget'],
},
];
if (typeof Ecwid != 'undefined') {
} else {
var script = document.createElement('script');
script.charset = 'utf-8';
script.type = 'text/javascript';
script.id = 'ecwid-script';
script.src = 'https://app.ecwid.com/script.js?xxx&data_platform=code&data_date=2021-01-14';
document.getElementById('my-store-xxx').appendChild(script);
}
};
componentDidMount() {
this.loadEcwid();
this.setState({ isLoaded: true });
console.log('loaded!');
this.render();
}
render() {
return (
<div>
<div id="my-search-xxx" />
<div id="my-store-xxx" />
<div id="productBrowser" />
<div id="my-categories-xxx" />
<div className="ec-cart-widget" />
</div>
);
}
}
export default withRouter(EcwidStore);

你不应该在componentDidMount()中调用你的render()方法,你的组件应该在状态更新时重新渲染。因此,也许可以尝试从componentDidMount()中删除this.render()调用,并在loadEdwic方法结束时使用setState

使用组件更新方法,如shouldComponentUpdatecomponentDidUpdate,可能有助于您在调试过程中。

最新更新