项目地址:https://github.com/daniel-dx/nice-hooks/blob/master/README_CN.md
可以更方便的使用hooks。
useSingleState 替代useState
# Example
import React from "react";
import { useSingleState } from "nice-hooks";
export const UseSingleStateDemoComp = () => {
const [state, setState] = useSingleState({
count: 0,
time: +new Date()
});
function doSomeActions() {
console.log("Current count:", state.count);
}
return (
<div>
<h2>useSingleState</h2>
<p>{state.count} {state.time}</p>
<button
type="button"
onClick={() =>
setState(
{
count: state.count + 1
},
doSomeActions
)
}
>
Increase
</button>
<button type="button"
onClick={() =>
setState({
time: +new Date()
})
}
>
Chnange Time
</button>
</div>
);
};
useSingleInstanceVar 替代useRef
# Example
import React from "react";
import { useSingleInstanceVar, useSingleState } from "nice-hooks";
export const UseSingleInstanceVarDemoComp = () => {
const instanceVal = useSingleInstanceVar({
interval: null
});
const [state, setState] = useSingleState({ count: 0 });
function start() {
instanceVal.interval = setInterval(
() => setState({ count: state.count + 1 }),
1000
);
}
function stop() {
const interval = instanceVal.interval;
interval && clearInterval(interval);
}
return (
<div>
<p>{state.count}</p>
<button type="button" onClick={start}>Start</button>
<button type="button" onClick={stop}>Stop</button>
</div>
);
};