hooks
定义
- 类型
interface Props {
name: string;
}
const Comp: FunctionComponent<Props> = observer((props) => {
const [visible, setVisible] = useState(false);
const [peoples, setPeoples] = useState<People[]>([]);
const [selectIds, setSelectIds] = useState<string[]>([]);
return <div />;
});
- 默认 props
Comp.defaultProps = {
name: "赵日天",
};
坑
- 防抖等函数,因为函数变了而没执行,必须自己封装一次,用ref存起来timer
function useThrottle(fn, delay, dep: any[] = []) {
const { current } = useRef<any>({ fn, timer: null })
useEffect(
function() {
current.fn = fn
},
[fn]
)
return useCallback(function f(this: any, ...args) {
if (!current.timer) {
current.timer = setTimeout(() => {
delete current.timer
}, delay)
current.fn.call(this, ...args)
}
}, dep)
}
- 函数间互相调用导致的变量还没更新,因为函数还是旧的
useState返回的是不可变
解决方案:
1、采用useRef, 好麻烦const currentPageRef = useRef(1); currentPageRef.current = 1;
2、手动传参给函数, 好麻烦const getData = async (currentPage) => {}
3、用监听, 更麻烦了,要是有多个变量useEffect(()=>{}, currentPage)
4、使用useEffect来监听变量而执行函数
特殊解决方法 useRefState
import { useEffect, useRef, useState } from "react";
const useRefState = <T>(
initialValue: T
): [T, React.MutableRefObject<T>, React.Dispatch<React.SetStateAction<T>>] => {
const [state, setState] = useState<T>(initialValue);
const stateRef = useRef(state);
useEffect(() => {
stateRef.current = state;
}, [state]);
return [state, stateRef, setState];
};
export default useRefState;
useState
定义变量
const Comp: FunctionComponent<Props> = () => {
const [count, setCount] = useState(0);
return (
<View>
Count: {count}
<Button onClick={() => setCount(initialCount)}>Reset</Button>
<Button onClick={() => setCount(prevCount => prevCount + 1)}>+</Button>
<Button onClick={() => setCount(prevCount => prevCount - 1)}>-</Button>
</View>
}
useEffect
- 生命周期
const didMount = async () => {
await getData();
};
const unMount = () => {};
useEffect(() => {
didMount();
return () => {
unMount();
};
});
- 监听变量
const [count, setCount] = useState(0);
useEffect(() => {
console.log("count变了", count);
}, [count]);
useCallback
性能优化内部函数,根据后面的[]来判断是否更新函数
感觉不用也行。。除非你的是 for 循环,有大量界面刷新
const [visible, setVisible] = useState(false);
const close = useCallback(() => {}, [visible]);
useRef
定义引用组件或者其他特殊东西
- 定时器
() => {
const timerID = useRef();
useEffect(() => {
timerID.current = setInterval(() => {
setCount((count) => count + 1);
}, 1000);
}, []);
useEffect(() => {
if (count > 10) {
clearInterval(timerID.current);
}
});
};
- 原始组件
const scrollRef = useRef<HTMLDivElement>(null);
scrollRef.current.clientHeight
<div className="msgList" ref={scrollRef} onScroll={onScroll}></div>
- 调用子组件
子组件
export interface SelectPeopleModalHandle {
open: (option: Option) => any;
}
/** 选择人员弹窗 */
const SelectPeopleModal: FunctionComponent<Props> = (props, ref) => {
const open = useCallback(() => {}, []);
useImperativeHandle(
ref,
() => ({
open: open,
}),
[open]
);
return <Modal></Modal>;
};
export default observer(forwardRef(SelectPeopleModal));
父组件
import SelectPeopleModal, { SelectPeopleModalHandle } from "../components/SelectPeopleModal";
() => {
const selectPeopleModalRef = useRef<SelectPeopleModalHandle>(null);
const open = () => {
selectPeopleModalRef.current!.open();
};
return <SelectPeopleModal ref={selectPeopleModalRef} />;
};
useReducer
尽量别用
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter({ initialState }) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<View>
Count: {state.count}
<Button onClick={() => dispatch({ type: "increment" })}>+</Button>
<Button onClick={() => dispatch({ type: "decrement" })}>-</Button>
</View>
);
}
useMemo
缓存大量计算的值
传入 useMemo 的函数会在渲染期间执行。请不要在这个函数内部执行与渲染无关的操作,诸如副作用这类的操作属于 useEffect 的适用范畴,而不是 useMemo
const memoizedValue = useMemo(() => {
return computeExpensiveValue(a, b);
}, [a, b]);
useContext
尽量少用
用于多层父子组件交互