我有一个 React 组件,它试图获取一些数据,并onSuccess(result)
在成功检索数据后调用回调。
我需要将数据保存到 redux。我创建了正在使用的自定义钩子useDispatch
,我正在尝试做这样的事情:
<MyComponent onSuccess = {res => myCustomHook(res)} />
但我收到一个错误,因为无法在回调中调用钩子。
我知道钩子只能在功能组件的顶层调用..那么我怎样才能实现我所需要的呢?
自定义钩子:
export function useSaveData(type, response)
{
if(!type|| !response)
{
throw new Error("got wrong parameters for useSaveData");
}
let obj= {
myData1: response.data1,
myData2: response.data2
};
sessionStorage.setItem(type, JSON.stringify(obj));
const dispatch = useDispatch();
dispatch(actionCreator.addAction(type, obj));
}
父组件可以将调度程序传递给useSaveData
如下。
export const useSaveData = (dispatch) => (type, response) =>
{
if(!type|| !response)
{
throw new Error("got wrong parameters for useSaveData");
}
let obj= {
myData1: response.data1,
myData2: response.data2
};
sessionStorage.setItem(type, JSON.stringify(obj));
dispatch(actionCreator.addAction(type, obj));
}
而父组件就变成了;
function ParentComponent() {
const dispatch = useDispatch();
const myCustomHook = useSaveData(dispatch);
return <MyComponent onSuccess = {res => myCustomHook(ACTION_TYPE, res)} />
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句