createStore
- 可通过 store 去访问或操作atom的值
- 如果 不通过 Provider 包裹着的话,
-
- 则组件内使用atom 着监听不到 通过 store.set() 更改 atom value (无论在组件内外)
- 组件的初始化值采用 传递给 atom 的第一个参数 如:atom(1)
- 在组件内使用 同一个atom 采用同一份数据,与 store 的数据是独立的
- 在 Provider 内的组件
-
- 即可通过 store.set 来初始化atom 值
- 在组件内外通过 store.set 更改数据,组件都能监听到atom value 的改变
- store 与 atom 的数据保持一致
- 通过 store.get() 或取数据是最新值,不同 useAtom 等, 需组件重新渲染后才是最新值
可以 通过 使用 store 的方法,替换掉与 Valtio 库相结合的方法实现在组件外部访问 atom 值, 如果使用 store, 务必在组件外部包裹 Provider
const testAtom = atom(1);
const store = createStore();
console.log("test atom value: ", store.get(testAtom));// 1
store.set(testAtom, 2);
console.log("test atom value: ", store.get(testAtom)); // 2
const Test = () => {
const [value, setValue] = useAtom(testAtom);
return <button onClick={() => {
setValue(value => value + 1);
console.log("log set: ", value, store.get(testAtom))
}}>{value}</button>;
};
const setTestValue = (value: number) => store.set(testAtom, value)
const TestStore = () => {
const currentValue = store.get(testAtom);
console.log("read store value: ", currentValue)
return <>
<button onClick={() => setTestValue(currentValue + 1)}>store: {currentValue}</button>
<button onClick={() => console.log("log:", store.get(testAtom))}>log: {currentValue}</button>
</>;
};
<Provider store={store}>
<Test />
<Test />
<TestStore />
</Provider>