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

[React] useState 和 useReducer 的相互实现 #46

Open
PeterChen1997 opened this issue Jul 24, 2022 · 0 comments
Open

[React] useState 和 useReducer 的相互实现 #46

PeterChen1997 opened this issue Jul 24, 2022 · 0 comments
Labels

Comments

@PeterChen1997
Copy link
Owner

useReducer 实现 useEffect

const useState = (initState) => {
    const reducer = (prev, action) => {
        return typeof action === "function" ? action(prev) : action;
    };

    return useReducer(reducer, initState);
};

useEffect 实现 useReducer

const useReducer = (reducer, initState) => {
    const [state, setState] = useState(initState);

    const dispatch = (action) => {
        setState((prev) => reducer(prev, action));
    };

    return [state, dispatch];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant