在react开发过程中,难免会遇到setState某个变量后直接使用的问题。一般定义如下: const [a,setA] = useState(0); 那setA后要直接使用a的时候要怎么处理呢?
方案一:
参考别人的方案是自定义一个hook,返回ref的值。如下
const useGetState = (initVal) => {
const [state, setState] = useState(initVal);
const ref = useRef(initVal);
const setStateCopy = (newVal) => { ref.current = newVal; setState(newVal); }
const getState = () => ref.current;
return [state, setStateCopy, getState]; }
//使用
const [arr, setArr, getArr] = useGetState([0]);
这个getArr就是同步的变量了。
这种方案需要自定义hook。
方案二
let [state,setState]=useState(0);
//某个方法修改state
const changeState=()=>{
state=1;
setState(state)
}
//这样就可以直接拿到最新的state了。
那么问题来了,这样使用有啥弊端吗?请高手告知下。