首页 > 解决方案 > NextJS 将数据推送到变量实际上不起作用

问题描述

我正在尝试将数据推送到包含 id 的变量。这是声明此类变量的代码:

var ids = [];

我有一个 element.onclick,每当他们单击它时,它都会切换选择并决定是否应该删除或将 id 推送到数组。

这是那个的代码

    function appendImgClick(appendTo, id){
        let li = document.createElement("li");
        li.setAttribute("class", "thingtopick");
        let img = document.createElement("img");
        img.selected = false;
        img.setAttribute("class", "thing");
        img.onclick = function(e){
            if (img.selected){
                img.setAttribute("class", "thing");
                array_remove_index_by_value(ids, id);
            }
            else{
                img.setAttribute("class", "thing selected");
                addToItemList(id);
                // I've already tried just doing ids.push(id) that did not work, so I used a function that would do that thinking it would be serverside/clientside or something but no.
            }
            img.selected = !img.selected;
        }
        li.append(img);
        appendTo.append(li);
        fetch(`/api/item-thumbnail/${limitedId}`).then(e=>e.json().then(e=>{
            img.src = e.data[0].imageUrl;
        }));
    }
    ```

我能做些什么来完成这项工作?

整个事情都在 nextjs 中(在 /pages/select.js 下),它不是React 组件,它的声明如下:```

export default function page()

标签: node.jsnext.js

解决方案


好的,所以我实际上在搞砸了一点之后找到了自己的解决方法,将所有函数移到导出默认函数 page(){} 函数之外,这样列表就可以很好地通过保存了。

tldr:将功能移到导出默认功能页面之外。


推荐阅读