简体   繁体   English

在查询后向搜索命中添加属性并在 InstantSearch.js 中动态重新呈现

[英]Adding attributes to search hits after query and dynamically re-render in InstantSearch.js

I am setting up InstantSearch icw Algolia for products of a webshop with the plain JavaScript implementation.我正在为具有普通 JavaScript 实现的网上商店的产品设置 InstantSearch icw Algolia。 I am able to follow all the documentation, but I am running into the problem that we have prices specific to customer groups, and things like live stock information (need to do another API call for that).我能够遵循所有文档,但我遇到了一个问题,即我们有特定于客户群体的价格,以及诸如实时库存信息之类的东西(需要再次拨打 API 电话)。

These attributes I would like to ideally load after getting search results, from our own back-end.我希望在获得搜索结果后从我们自己的后端理想地加载这些属性。

I thought it would simply be a matter of manipulating the search results after receiving them and re-rendering only the front-end (without calling the Algolia search API again for new results).我认为这只是在收到搜索结果后对其进行操作并仅重新呈现前端的问题(无需再次调用 Algolia 搜索 API 获取新结果)。

This is a bit tricky.这有点棘手。 The transformItems functionality is possible, but I want to already display the results and load the other data into the hit templates after, not before displaying the hit results. transformItems 功能是可能的,但我希望已经显示结果并将其他数据加载到命中模板中,而不是在显示命中结果之前。

So I end up with a custom widget, and I can access and manipulate the results there, but here the problem is that I don't know how to reflect these changes into the rendered templates.所以我最终得到了一个自定义小部件,我可以在那里访问和操作结果,但这里的问题是我不知道如何将这些更改反映到呈现的模板中。

The code of my widget (trying to set each stock number to 9) is as follows:我的小部件的代码(尝试将每个股票编号设置为9)如下:

{
    render: function(data) {
        const hits = data.results.hits;

        hits.forEach(hit => {
            hit.stock = 9
        });
    }
}

The data is changed, but the generated html from the templates does not reflect any changes to the hit objects.数据已更改,但从模板生成的 html 并未反映命中对象的任何更改。

So how could I trigger a re-render after altering the hits data, without triggering a new search query?那么,如何在更改命中数据后触发重新呈现,而不触发新的搜索查询?

I could not find a function to do this anywhere in the documentation.我在文档中的任何地方都找不到 function 来执行此操作。

Thanks!谢谢!

There is the transformItems function in the hits widget that allows you to transform, remove or reorder items as you wish. hits 小部件中有 transformItems function,可让您根据需要转换、删除或重新排序项目。 It is called before items displaying.它在项目显示之前被调用。

If I use your example, it would be something like this:如果我使用你的例子,它会是这样的:

transformItems(items) {
  return items.map(item => ({
    ...item,
    stock: 9,
  }));
}

Of course you can add you API call somewhere in that.当然,您可以在其中某处添加 API 电话。

The documentation for the vanilla JS library: vanilla JS 库的文档:

https://www.algolia.com/doc/api-reference/widgets/hits/js/#widget-param-transformitems https://www.algolia.com/doc/api-reference/widgets/hits/js/#widget-param-transformitems

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM