有时候,咱们在以后组件里注册了第三方插件的事件回调,回掉函数的参数是第三方抛出来的数据,咱们在这个回掉里,可能还须要拜访以后组件里state,然而你很有可能就会遇到始终拿到的是第一次的state,上面开始上代码。
const [info, setInfo] = useState();
const [isEnd, setIsEnd] = useState(false);
useEffect(() => {
const callBackId1 = Plus.reigsterCallBack1((info) => {
setInfo(info);
});
const callBackId2 = Plus.reigsterCallBack2(info2 => {
if (info2.id === info.id) {
//这里的info将会永远都是null
setIsEnd(true);
}
});
return () => {
Plus.unregisterCallBack(callBackId1);
Plus.unregisterCallBack(callBackId2);
};
}, []);
计划1: useRef
const [info, setInfo] = useState();
const [isEnd, setIsEnd] = useState(false);
const instRef = useRef();//新增
useEffect(() => {
const callBackId1 = Plus.reigsterCallBack1((info) => {
setInfo(info);
instRef.current = info;//新增
});
const callBackId2 = Plus.reigsterCallBack2(info2 => {
if (info2.id === instRef.current.id) {//批改
setIsEnd(true);
}
});
return () => {
Plus.unregisterCallBack(callBackId1);
Plus.unregisterCallBack(callBackId2);
};
}, []);
计划2:useCallback
const [info, setInfo] = useState();
const [isEnd, setIsEnd] = useState(false);
const callBack2 = useCallback(//新增
info2 => {
if (info2.id === info.id) {
setIsEnd(true);
}
},
[info]
);
useEffect(() => {
const callBackId1 = Plus.reigsterCallBack1((info) => {
setInfo(info);
instRef.current = info;
});
const callBackId2 = Plus.reigsterCallBack2(callBack2);//批改
return () => {
Plus.unregisterCallBack(callBackId1);
Plus.unregisterCallBack(callBackId2);
};
}, [callBack2]);//批改
发表回复