Skip to content

rxv 最简实现 #5

@cevio

Description

@cevio

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

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

这样就行了。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions