面试题答案
一键面试createMemo的作用
在Solid.js中,createMemo
用于创建一个响应式的计算值。它会缓存其返回值,只有当它所依赖的响应式数据发生变化时,才会重新计算。这有助于避免不必要的计算,提高应用性能,特别是在计算成本较高的场景下。
示例代码
import { createSignal, createMemo } from 'solid-js';
const App = () => {
const [count, setCount] = createSignal(0);
const [otherValue, setOtherValue] = createSignal(10);
const memoizedValue = createMemo(() => {
// 这里模拟一个复杂计算
return count() * otherValue();
});
return (
<div>
<p>Count: {count()}</p>
<p>Other Value: {otherValue()}</p>
<p>Memoized Value: {memoizedValue()}</p>
<button onClick={() => setCount(count() + 1)}>Increment Count</button>
<button onClick={() => setOtherValue(otherValue() + 1)}>Increment Other Value</button>
</div>
);
};
export default App;
在上述示例中,memoizedValue
依赖于count
和otherValue
这两个响应式数据。只有当count
或otherValue
发生变化时,memoizedValue
才会重新计算。