我如何简单地改变信号内的数组

How do I simply mutate the array inside a signal

这是一个工作示例,但有问题。我想在一个信号中拼接一个现有的数组,然后 return 它以查看它的更新。但它不起作用。我如何简单地改变信号内的数组?我不想创建新数组只是一个简单的拼接。文档中没有关于改变数组的示例。

import {  render } from 'solid-js/web';
import { createSignal, createEffect } from 'solid-js'

function HelloWorld() {
  let [a, setA] = createSignal([])

  setTimeout(() => 
  setA(a => {
    a.splice(0, 0, 'hello')
    // this logs as requested if I uncomment this
    //return ['hello']
    return a
  }))


  createEffect(() => {
    console.log(a())
  })
  return <div>Hello World!</div>;
}

render(() => <HelloWorld />, document.getElementById('app'))

实体教程strongly recommends immutability:

Solid strongly recommends the use of shallow immutable patterns for updating state. By separating reads and writes we maintain better control over the reactivity of our system without the risk of losing track of changes to our proxy when passed through layers of components.

实现目标的不可变方法可能如下所示:

setA(a => ['hello', ...a])

但是,如果您确定必须 改变信号,您可以指定 Solid 如何确定信号是否已在 createSignal's options object 内更新。默认情况下,使用 === 运算符通过 引用相等性 比较信号变化。在调用 setter 之后,您可以通过将 equals 设置为 false:

来告诉 Solid 总是 re-run 依赖项
let [a, setA] = createSignal([], { equals: false });

或者您可以传递一个函数,该函数采用信号的 previousnext 值以及 returns a boolean:

let [a, setA] = createSignal([], { equals: (prev, next) => {
  if (/* dependents should run */) {
    return false;
  }
  // dependents shouldn't run
  return true;
} });