如何在回调中调用 useDispatch [英] How to call useDispatch in a callback

查看:56
本文介绍了如何在回调中调用 useDispatch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 React 组件,它试图获取一些数据,并在成功检索数据后调用 onSuccess(result) 回调.

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.

我需要将数据保存到 redux.我创建了使用 useDispatch 的自定义钩子,我正在尝试做这样的事情:

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?

自定义钩子:

    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));
  }

推荐答案

父组件可以将 dispatcher 传递给 useSaveData 如下.

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));
  }

和父组件变成;

function ParentComponent() {
    const dispatch = useDispatch();
    const myCustomHook = useSaveData(dispatch);
    return <MyComponent onSuccess = {res => myCustomHook(ACTION_TYPE, res)} />
}

这篇关于如何在回调中调用 useDispatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆