useState是最常用的hook了,就不介绍了。
useState可以通过调用callback获取最新的state。方便解决异步调用时获取的state是创建异步时的state而无法获取到最新state的情况。
const [state, setState] = useState(initialState);
useState(lastState=>{
//get newest state.
//do something to last state, example: use ... to clone an array or object and modify it.
return newState;
}
useEffect是
useRef实在是太好用了有木有!!!
useRef类似一个盒子,可以在.current属性里保存任何可变值,不需要类似于useState一样异步存在延迟,屯在最后一次性更新,而是随时随地更新,方便快捷!
//use useRef to log the audio amplitude of a recording
const context = new AudioContext();
const recorder = context.createScriptProcessor(4096, 1, 1);
recorder.onaudioprocess = function(e) {
const inputFrame = e.inputBuffer.getChannelData(0);
const maxvo = Math.max.apply(null, inputFrame);
if (maxvo > maxVolume.current)
maxVolume.current = maxvo;//if use setState, it will log the lastest value bigger than initial value.
};
navigator.mediaDevices
.getUserMedia(mediaConstraints)
.then(stream => {
const audioInput = context.createMediaStreamSource(stream);
audioInput.connect(recorder);
recorder.connect(context.destination);
})
.catch(e => {
console.error(`Recording Error: ${e}`);
});
配合ref使用,让父组件也可以时时刻刻获取到子组件的ref。
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
//渲染 <FancyInput ref={inputRef} /> 的父组件可以调用 inputRef.current.focus()。
父组件传给子组件,可以穿透多层子组件。可以父组件用setState更新,子组件也可以随时获取最新值。
//父组件
export const StateContext= React.createContext<{
state: string[];
setState: (state: string[]) => void;
}>(null);
const [state, setState] = useState(null);
<StateContext.Provider value={{ historyProjects, setHistoryProjects }}>
<SubComponent />
</StateContext.Provider>
//子组件
const { state, setState} = useContext(StateContext);
适用于boolean的state。
export function useBoolean(
initialState: boolean
): [boolean, { setTrue: () => void; setFalse: () => void; toggle: () => void }] {
const [value, setValue] = useState(initialState);
const setTrue = () => setValue(true);
const setFalse = () => setValue(false);
const toggle = () => setValue(x => !x);
return [value, { setTrue, setFalse, toggle }];
}
//使用
const [isOpen, { setTrue: openPanel, setFalse: dismissPanel, toggle: togglePanel }] = useBoolean(false);
openPanel();//打开panel
dismissPanel();//关闭panel
togglePanel();//打开时关闭,关闭时打开
重置初始状态
export function useResetState<S>(initialState?: S): [S, Dispatch<SetStateAction<S>>, () => void] {
const [state, setState] = useState(initialState);
const resetState = () => setState(initialState);
return [state, setState, resetState];
}
//使用
const [itemToEdit, setItemToEdit, resetItemToEdit] = useResetState(null as TTSProject);
setItemToEdit(item);
resetItemToEdit();//重置成初始状态
原文:https://www.cnblogs.com/xym4869/p/14049852.html