如何在回调中调用useSelector

时间:2019-12-24 08:18:46

标签: reactjs react-redux react-hooks

这是该问题的后续问题:

How to call useDispatch in a callback

我有一个React组件,需要从其道具中的redux接收信息。该信息是使用自定义钩子获取的。

这是自定义挂钩:

  export function useGetData(selectorFunc)
  {
    return type =>
    {
      if(!type)
      {
        throw new Error("got a wrong type");
      }
      let myData = selectorFunc(state => 
      {
        let res = JSON.parse(sessionStorage.getItem(type));
        if(!res )
        {
          res = state.myReducer.myMap.get(type);
        }
        return res;
      });
      return myData;
    }
  }

基于链接问题的答案,我尝试执行以下操作:

function Compo(props)
{
   const getDataFunc = useGetData(useSelector);
   return <MyComponent dataNeeded = { getDataFunc(NeededType).dataNeeded } />
}

但出现错误,因为无法在回调内部调用挂钩。

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

不要通过选择器,只需使用它即可。

此外,根据您的逻辑,您还应该在选择器之外解析存储密钥。

export function useDataFunc() {
  const myData = useSelector(state => myReducer.myMap);

  const getDataFunc = type => {
    const resByData = myData.get(type);
    try {
      // JSON.parse can throw an error!
      const res = JSON.parse(sessionStorage.getItem(type));
    } catch (e) {
      return resByData;
    }
    return res ? res : resByData;
  };
  return getDataFunc;
}

function Compo(props) {
  const getDataFunc = useDataFunc();
  return <MyComponent dataNeeded={getDataFunc(NeededType).dataNeeded} />;
}