MST

星途 面试题库

面试题:Solid.js中createMemo基础应用

在Solid.js中,简述createMemo的作用。请编写一个简单示例,展示使用createMemo缓存一个计算值,且该计算值依赖于其他响应式数据。
47.9万 热度难度
前端开发Solid.js

知识考点

AI 面试

面试题答案

一键面试

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依赖于countotherValue这两个响应式数据。只有当countotherValue发生变化时,memoizedValue才会重新计算。