Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rxv 最简实现 #5

Open
cevio opened this issue Mar 22, 2021 · 0 comments
Open

rxv 最简实现 #5

cevio opened this issue Mar 22, 2021 · 0 comments

Comments

@cevio
Copy link

cevio commented Mar 22, 2021

经过我长时间的使用,你的方案确实不错,但是还有更简的写法,没必要写的如你这般复杂:

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>
}

这样就行了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant