在以下代码示例中:
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 时的消息 - 永远不会显示......
知道我在这里错过了什么吗?
您似乎没有遵循说明。在 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
。同样,您应该阅读的文档中对此进行了介绍。