面试题答案
一键面试模拟 componentDidMount
在 Solid.js 中,createEffect
函数会在组件首次渲染后立即执行,这类似于 componentDidMount
。
import { createEffect, createSignal } from 'solid-js';
const MyComponent = () => {
const [count, setCount] = createSignal(0);
createEffect(() => {
console.log('Component has mounted');
// 在这里可以执行只在组件挂载后运行一次的代码,比如初始化某些外部库
});
return (
<div>
<p>Count: {count()}</p>
<button onClick={() => setCount(count() + 1)}>Increment</button>
</div>
);
};
export default MyComponent;
模拟 componentDidUpdate
createEffect
结合依赖数组可以模拟 componentDidUpdate
。每当依赖的值发生变化时,该副作用函数就会重新执行。
import { createEffect, createSignal } from 'solid-js';
const MyComponent = () => {
const [count, setCount] = createSignal(0);
createEffect(() => {
const currentCount = count();
console.log(`Count has updated to: ${currentCount}`);
// 在这里可以执行依赖变化时需要运行的代码
}, [count()]);
return (
<div>
<p>Count: {count()}</p>
<button onClick={() => setCount(count() + 1)}>Increment</button>
</div>
);
};
export default MyComponent;
模拟 componentWillUnmount
onCleanup
函数可以在组件卸载时执行清理操作,类似于 componentWillUnmount
。它通常在 createEffect
内部使用。
import { createEffect, createSignal, onCleanup } from 'solid-js';
const MyComponent = () => {
const [count, setCount] = createSignal(0);
createEffect(() => {
// 模拟一些需要清理的操作,比如订阅事件
const subscription = () => console.log('Subscription');
onCleanup(() => {
console.log('Component is about to unmount');
// 在这里取消订阅或清理其他资源
subscription();
});
});
return (
<div>
<p>Count: {count()}</p>
<button onClick={() => setCount(count() + 1)}>Increment</button>
</div>
);
};
export default MyComponent;