面试题答案
一键面试在Solid.js中,计算属性通过createMemo
来创建,它会自动追踪其依赖关系。当依赖发生变化时,计算属性会重新计算。
以下是代码示例:
import { createSignal, createMemo } from 'solid-js';
// 创建两个信号
const [count, setCount] = createSignal(0);
const [otherValue, setOtherValue] = createSignal(10);
// 创建计算属性
const sum = createMemo(() => count() + otherValue());
// 渲染视图
const App = () => (
<div>
<p>Count: {count()}</p>
<p>Other Value: {otherValue()}</p>
<p>Sum: {sum()}</p>
<button onClick={() => setCount(count() + 1)}>Increment Count</button>
<button onClick={() => setOtherValue(otherValue() + 1)}>Increment Other Value</button>
</div>
);
export default App;
在上述代码中:
createMemo
创建了sum
计算属性,其依赖于count
和otherValue
两个信号。- 当
count
或otherValue
的值发生变化时(通过setCount
或setOtherValue
函数),sum
计算属性会自动重新计算。 - 由于Solid.js的细粒度响应式系统,只有依赖变化的计算属性和相关视图部分会被更新,而非整个组件重新渲染,提升了性能。