React 组件不对计算信号做出反应

问题描述 投票:0回答:1

在以下代码示例中:

import React from 'react';
import { signal, computed } from '@preact/signals-react';

const App: React.FC = () => {
  const count = signal<number>(0);
  const countIsMoreThanTwo = computed<boolean>(() => count.value > 2);

  console.log('CHECKS:', count.value, countIsMoreThanTwo.value);

  return (
    <>
      <h1>Vite + React</h1>
      {countIsMoreThanTwo.value && <h2>More than 2</h2>}
      <h3>Count is more than two: { countIsMoreThanTwo }</h3>
      <button onClick={() => count.value++}>
        count is { count }
      </button>
    </>
  )
}
export default App;

这里计数更新反映在 JSX 中,但是当计数 > 2 时的消息 - 永远不会显示......

知道我在这里错过了什么吗?

reactjs signals
1个回答
0
投票

您似乎没有遵循说明。在 React 中,您必须使用 Babel 插件 自动转换组件,或者在每个需要订阅信号的组件中手动添加

useSignals()
钩子。

这是

useSignals()
选项的示例:

import React from 'react';
import { useSignal, useComputed } from '@preact/signals-react';
import { useSignals } from "@preact/signals-react/runtime";

const App: React.FC = () => {
  useSignals();
  const count = useSignal<number>(0);
  const countIsMoreThanTwo = useComputed<boolean>(() => count.value > 2);

  console.log('CHECKS:', count.value, countIsMoreThanTwo.value);

  return (
    <>
      <h1>Vite + React</h1>
      {countIsMoreThanTwo.value && <h2>More than 2</h2>}
      <h3>Count is more than two: { countIsMoreThanTwo }</h3>
      <button onClick={() => count.value++}>
        count is { count }
      </button>
    </>
  )
}
export default App;

此外,您不能在组件内使用

signal
computed
——您必须使用
useSignal
useComputed
。同样,您应该阅读的文档中对此进行了介绍。

© www.soinside.com 2019 - 2024. All rights reserved.