项目地址:https://github.com/daniel-dx/nice-hooks/blob/master/README_CN.md

    可以更方便的使用hooks。

    useSingleState 替代useState

    1. # Example
    2. import React from "react";
    3. import { useSingleState } from "nice-hooks";
    4. export const UseSingleStateDemoComp = () => {
    5. const [state, setState] = useSingleState({
    6. count: 0,
    7. time: +new Date()
    8. });
    9. function doSomeActions() {
    10. console.log("Current count:", state.count);
    11. }
    12. return (
    13. <div>
    14. <h2>useSingleState</h2>
    15. <p>{state.count} {state.time}</p>
    16. <button
    17. type="button"
    18. onClick={() =>
    19. setState(
    20. {
    21. count: state.count + 1
    22. },
    23. doSomeActions
    24. )
    25. }
    26. >
    27. Increase
    28. </button>
    29. <button type="button"
    30. onClick={() =>
    31. setState({
    32. time: +new Date()
    33. })
    34. }
    35. >
    36. Chnange Time
    37. </button>
    38. </div>
    39. );
    40. };

    useSingleInstanceVar 替代useRef

    1. # Example
    2. import React from "react";
    3. import { useSingleInstanceVar, useSingleState } from "nice-hooks";
    4. export const UseSingleInstanceVarDemoComp = () => {
    5. const instanceVal = useSingleInstanceVar({
    6. interval: null
    7. });
    8. const [state, setState] = useSingleState({ count: 0 });
    9. function start() {
    10. instanceVal.interval = setInterval(
    11. () => setState({ count: state.count + 1 }),
    12. 1000
    13. );
    14. }
    15. function stop() {
    16. const interval = instanceVal.interval;
    17. interval && clearInterval(interval);
    18. }
    19. return (
    20. <div>
    21. <p>{state.count}</p>
    22. <button type="button" onClick={start}>Start</button>
    23. <button type="button" onClick={stop}>Stop</button>
    24. </div>
    25. );
    26. };