面试题答案
一键面试createStore工作原理
- 状态管理基础:在Solid.js中,
createStore
用于创建一个响应式的存储对象。它接受一个初始状态对象作为参数,并返回一个包含状态对象和一个更新函数的数组。例如:
import { createStore } from 'solid-js';
const [store, setStore] = createStore({
count: 0
});
这里 store
是包含初始状态 {count: 0}
的响应式对象,setStore
是用于更新这个状态的函数。
- 响应式机制:Solid.js 使用细粒度的响应式系统。当
createStore
创建的状态发生变化时,依赖于该状态的组件会自动重新渲染。这种重新渲染基于组件中对状态的引用,只有使用到变化状态的组件才会更新,而不是整个组件树。例如,有一个显示count
的组件:
import { createStore } from'solid-js';
import { render } from'solid-js/web';
const [store, setStore] = createStore({
count: 0
});
const App = () => {
return <div>{store.count}</div>;
};
render(() => <App />, document.getElementById('app'));
当调用 setStore
更新 store.count
时,App
组件会重新渲染以显示新的值。
与Context API结合时数据传递与更新
- Context API 基础:Solid.js 的 Context API 用于在组件树中共享数据,而无需通过层层传递 props。它由
createContext
和Provider
以及useContext
组成。
import { createContext, Provider } from'solid-js';
const MyContext = createContext();
const Parent = () => {
return (
<Provider value={{ data: '一些共享数据' }} context={MyContext}>
<Child />
</Provider>
);
};
const Child = () => {
const context = useContext(MyContext);
return <div>{context.data}</div>;
};
- 结合
createStore
:当createStore
与 Context API 结合时,createStore
创建的响应式状态可以通过 Context 传递。这样,任何层级的组件都可以访问和更新这个共享状态,并且更新会触发依赖组件的响应式更新。例如:
import { createStore, createContext, Provider, useContext } from'solid-js';
import { render } from'solid-js/web';
const [store, setStore] = createStore({
message: '初始消息'
});
const MyContext = createContext();
const Parent = () => {
return (
<Provider value={{ store, setStore }} context={MyContext}>
<Child />
</Provider>
);
};
const Child = () => {
const { store, setStore } = useContext(MyContext);
const updateMessage = () => {
setStore('message', '更新后的消息');
};
return (
<div>
<p>{store.message}</p>
<button onClick={updateMessage}>更新消息</button>
</div>
);
};
render(() => <Parent />, document.getElementById('app'));
在这个例子中,Parent
组件通过 Provider
将 createStore
创建的 store
和 setStore
传递到 Context 中。Child
组件通过 useContext
获取这些值,当点击按钮调用 setStore
更新 message
时,Child
组件会响应式地更新显示新的消息。