问题
I got a React component which is trying to get some data, and is calling an onSuccess(result) call back upon a successful retrieval of data.
I need to save the data to redux. I created custom hooks which are using useDispatch, and I'm trying to do something like this:
<MyComponent onSuccess = {res => myCustomHook(res)} />
but I get an error because an hook can not be called inside a callback.
I know that hooks can only be called at the top level of a functional component.. So how can I achieve what I need?
The custom hook:
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));
}
回答1:
The parent component could pass dispatcher to useSaveData as follows.
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));
}
And parent component becomes;
function ParentComponent() {
const dispatch = useDispatch();
const myCustomHook = useSaveData(dispatch);
return <MyComponent onSuccess = {res => myCustomHook(ACTION_TYPE, res)} />
}
回答2:
Your custom hook should return a function which can be passed as callback.
useMyCustomHook = () => {
// your hook
const onSuccess = () => {
// save data here
}
return { onSuccess };
}
In your component.
function MyComponent(props) {
const { onSuccess } = useMyCustomHook();
// your component code, you have onSuccess which can be bind with button or form as per your requirement.
}
Edit after seeing your custom hook.
You don't need to create custom hook here. you can simply pass dispatch to your callback.
const dispatch = useDispatch()
<MyComponent onSuccess={res => onSuccess(res, dispatch)} />
create onSucces function.
export function onSuccess(type, response, dispatch)
{
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));
}
来源:https://stackoverflow.com/questions/59456816/how-to-call-usedispatch-in-a-callback