【问题标题】:Reload render function after componentDidMount is loaded加载 componentDidMount 后重新加载渲染函数
【发布时间】:2021-05-03 10:50:34
【问题描述】:

我正在尝试在我的 react.js 网站上加载 ecwid 商店。 我创建了一个类组件,其中有一个名为 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);

【问题讨论】:

    标签: javascript reactjs react-class-based-component


    【解决方案1】:

    您不必在componentDidMount() 中调用您的render() 方法,您的组件应该在状态更新时重新呈现。因此,也许尝试从componentDidMount() 中删除您的this.render() 调用,并在您的loadEdwic 方法的末尾使用setState

    在调试过程中使用shouldComponentUpdatecomponentDidUpdate 等组件更新方法也可能对您有所帮助。

    【讨论】:

    • 我放了那个函数,因为我希望 html 在函数加载后运行。删除 this.render 函数对输出没有任何影响。我已经尝试过状态方法
    猜你喜欢
    • 2016-07-27
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多