-
Notifications
You must be signed in to change notification settings - Fork 7
Open
Description
经过我长时间的使用,你的方案确实不错,但是还有更简的写法,没必要写的如你这般复杂:
import { useEffect, useReducer } from "react";
import { effect, stop, ReactiveEffect } from '@vue/reactivity';
export function useReactiveState<T>(fn: () => T) {
const [state, dispatch] = useReducer((state: T, action: T) => action, fn());
useEffect(() => {
const _effect = effect(fn, {
lazy: true,
scheduler: (job: ReactiveEffect<T>) => dispatch(job()),
});
dispatch(_effect());
return () => stop(_effect);
}, []);
return state;
}使用方式:
import { ref } from '@vue/reactivity';
const count = ref(0);
const App = () => {
const num = useReactiveState(() => count.value);
return <div>
<button onClick={() => count.value++}>add 1</button>
<p>{num}</p>
</div>
}这样就行了。
wearzdk and chengzhuo5
Metadata
Metadata
Assignees
Labels
No labels