AlpineJS:如何创建和更新全局属性

huangapple go评论78阅读模式
英文:

AlpineJS: How to create and update global props

问题

我是阿尔派尼JS的新手。我对React有一些生产知识,对Vue也有一些基础知识。但是有一件事情我不太明白关于阿尔派尼JS,我在任何文档或教程视频中都没有找到直接的答案,这就是为什么我要问这个问题。显然是我的知识不足,但我担心对于每个新手来说都是如此。

假设我有以下代码(摘要):

<div x-data="{ array1 = [], array2 = [], total = 0 }">
    <!-- ✅ 成功:在这里获取用户输入并填充array1 -->
    <!-- ✅ 成功:在这里获取用户输入并填充array2 -->
    <button x-show="$store.total === 0; console.log('🚴‍♂️ ', $store.total)">
        做某事
    </button>
</div>

<script>
    const myFunc = (array1, array2, total) => {
        // 参考链接:https://stackoverflow.com/q/76607996/1743124
        const hash = array2.reduce((h, s) => {
            h[s] = (h[s] || 0) + 1;
            return h;
        }, {});

        array1.map(function(s) {
            if (hash[s] && hash[s]--) {
                console.log('🏌️‍♂️ total ', total);
                Alpine.store('total', total--); // ❓问题就在这里。
                console.log('🏄‍♂️ total-- ', total);
                return '✅' + s;
            } else {
                return s;
            }
        });
    }
</script>

myFunc 代码来自于这个 SO 线程

正如你所看到的,我已经实现了一些功能。我的问题是关于如何从 myFunc 函数内部更新 total 状态,并且可以在函数外部通用使用。

在React中,我们可以轻松地更新状态,如下所示:

// React JS的示例对比。

const [total, setTotal] = useState(0);

// 在某处 setTotal(500);

const myFunc = () => {
    setTotal(total--); // 在某个条件下在循环内部
    return true;
};

在这里,尽管函数返回了其他东西,但是状态是使用 setState 指令进行更新的,但我们可以在函数外部获得更新后的 total 值。

在阿尔派尼JS中如何做类似的事情呢?我理解可以使用全局的 Store 来实现,但它的效果不如预期。函数内部的控制台日志显示了我预期的内容,当它应该为零时,它显示为 1 ⚠️:

AlpineJS:如何创建和更新全局属性

我在这里做错了什么?
这是阿尔派尼JS中 Store 全局的预期效果吗?

PS. 我正在使用 @keyup 事件,当所有的事情都被触发时。

英文:

I'm new to AlpineJS. I have some production knowledge of React and some basics of Vue. But one of the things I'm not getting about AlpineJS and I did not find a direct answer to this from any of the documentation or tutorial videos on AlpineJS, that's why I'm asking this. It's obviously my lack of knowledge, but I'm afraid, that's true for every newcomer. AlpineJS:如何创建和更新全局属性

Suppose, I have the following code (summarized):

&lt;div x-data=&quot;{ array1 = [], array2 = [], total = 0 }&quot;&gt;
    &lt;!-- ✅ Success: Get user input and populate array1 here --&gt;
    &lt;!-- ✅ Success: Get user input and populate array2 here too --&gt;
    &lt;button x-show=&quot;$store.total === 0; console.log(&quot;&#128073; &quot;, $store.total)&quot;&gt;
        Do Something
    &lt;/button&gt;
&lt;/div&gt;

&lt;script&gt;
    const myFunc = (array1, array2, total) =&gt; {
        // Reference: https://stackoverflow.com/q/76607996/1743124
        const hash = array2.reduce((h, s) =&gt; {
            h
展开收缩
= (h
展开收缩
|| 0) + 1;
return h; }, {}); array1.map(function(s) { if(hash
展开收缩
&amp;&amp; hash
展开收缩
--) {
console.log(&quot;&#127948;️‍♂️ total &quot;, total); Alpine.store(&#39;total&#39;, total--); // &#128997; QUESTION IS HERE. console.log(&quot;&#128372;️ total-- &quot;, total); return &#39;✅&#39; + s; } else { return s; } }); } &lt;/script&gt;

The myFunc code is taken from this SO thread.

As you can see that I achieved some of the things. My question is about How can I update the total state from inside the function myFunc and that can be available outside the function for general use?

As in React, we can easily update a state like the below:

// REACT JS EXAMPLE FOR A CONTRAST.

const [total, setTotal] = useState(0);

// Somewhere setTotal(500);

const myFunc = () =&gt; {
    setTotal(total--); // under certain condition within a &#128260;️ loop
    return true;
};

Here, though the function is returning some other thing, the state is been updated using a setState directive, but we can get the updated value of total anywhere outside.

How can I do a similar thing in AlpineJS? I understood that it can be done using the Store global, but it's not working as expected. The console.logs inside the function were showing exactly what I expected, a 0 (zero) when it should be. But the console.log($store.total) is giving me 1 ⚠️:

AlpineJS:如何创建和更新全局属性

What am I doing wrong here?<br/>
Is this a desired effect of the Store global in AlpineJS?

PS. The event that I'm working with is @keyup when all the things are getting fired.

答案1

得分: 2

根据我所了解的一切,你只是困惑为什么在你的$storetotal的值是1,尽管它在一行后记录了"0"。这涉及到简单的JavaScript运算逻辑,适用于多种编程语言。

让我解释一下:你有一个"后减"和"前减"运算符(也适用于增加操作)。基本上取决于运算符是在变量之前(前减)还是之后(后减),其区别在于操作的顺序。在前减操作中,首先执行运算符,然后评估变量。在后减操作中,首先评估变量,然后执行运算符。

示例:

let x = 3;
let y = x--;
// x = 2, y = 3;

let x = 3;
let y = --x;
// x = 2, y = 2;

基本上正在发生的是,你正在存储total的值,然后再对其进行递减。如果你期望存储的值为0,你应该使用前减(--total)。

你可以在这里阅读更多详细信息。

英文:

From all I gather, you're simply confused as to why total is 1 within your $store, even though it logs "0" one line later. That's simple JS operator logic, which applies to multiple coding languages.

Let me explain: You have a "post-" and "pre-decrement" operator (also for increment). It's basically whether the operator is before (pre) or after (post) the variable, and the difference is the order of operations. In the pre operation, the operator is first executed, and then the variable is evaluated. In the post operator, the variable is first evaluated, and then the operator is executed.

Example:

let x = 3;
let y = x--;
// x = 2, y = 3;

let x = 3;
let y = --x;
// x = 2, y = 2;

Basically what is happening, is that you're storing the value of total, and then you're decrementing it. If you're expecting the stored value to be 0, you should use pre-decrement (--total).

You can read more details about it here.

huangapple
  • 本文由 发表于 2023年7月7日 04:33:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定