用 React 调用 Algolia search-insights 库

Call Algolia search-insights library with react

我正在尝试使用 React 从 algolia 实现 Search-Insights 库,并使用 npm 安装它,而不是像本示例中所述那样将其添加到 header。


React 实现示例

https://www.algolia.com/doc/guides/getting-insights-and-analytics/search-analytics/click-through-and-conversions/how-to/send-click-and-conversion-events-with-instantsearch/react/

<script>
  var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@1.3.1";

  !function(e,a,t,n,s,i,c){e.AlgoliaAnalyticsObject=s,e[s]=e[s]||function(){
  (e[s].queue=e[s].queue||[]).push(arguments)},i=a.createElement(t),c=a.getElementsByTagName(t)[0],
  i.async=1,i.src=n,c.parentNode.insertBefore(i,c)
  }(window,document,"script",ALGOLIA_INSIGHTS_SRC,"aa");

  // Initialize library
  aa('init', {
    appId: 'APPLICATION_ID',
    apiKey: 'SEARCH_API_KEY'
  });
</script>


使用NPM/yarn

https://www.algolia.com/doc/guides/getting-insights-and-analytics/personalization/personalizing-results/how-to/send-personalization-events-with-instantsearch/js/#install-the-search-insights-library

关于我的问题,我如何将 init 函数与 React 一起使用?我试过这样的东西

import searchInsights from "search-insights";

class LiveSearch extends React.Component {
  componentDidMount() {
    const appId = config.get("services.algolia.appId.live");
    const apiKey = config.get("services.algolia.apiKey.live");

    searchInsights("init", {
      appId: appId,
      apiKey: apiKey,
    });
  }
}

我收到这个错误

TypeError: search_insights__WEBPACK_IMPORTED_MODULE_23___default(...) is not a function

导入搜索洞察后,init 可用作 属性。所以像下面这样的东西应该可以工作

searchInsights.init({
   appId: "appId",
   apiKey: "apiKey",
});