反应钩子:从 useEffect 分派动作 [英] React hooks: dispatch action from useEffect

查看:23
本文介绍了反应钩子:从 useEffect 分派动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件夹结构:

|--App
  |--Components
    |--PageA.js
    |--PageB.js
    |--PageC.js
  |--common-effects
    |--useFetching.js

我正在重构我的代码以使用 react hooks 从 API 获取数据.我想从 useFetching.js 中的 useEffect 分派一个被 saga 中间件拦截的动作.仅当组件(PageAPageBPageC)挂载时才应分派该操作.

I am refactoring my code to fetch data from API, using react hooks. I want to dispatch an action from useEffect in useFetching.js that is intercepted by saga middleware. The action should be dispatched only when the components(PageA, PageB, PageC) mount.

我正在使用 reduxreact-reduxredux-saga.

I am using redux, react-redux and redux-saga.

PageA.js:

function(props) {
  useFetching(actionParams)
  //....//
}

PageBPageC 组件的类似代码.

Similar code for PageB and PageC components.

我在useFetching自定义钩子中抽象了可重用的代码来获取数据.

I have abstracted the reusable code to fetch data in useFetching Custom hook.

useFetching.js

const useFetching = actionArgs => {
  useEffect( () => {
    store.dispatch(action(actionArgs)); // does not work
  })
}

我不知道如何在 useFetching 中访问 redux dispatch.我用 useReducer 效果试过了,但传奇没有做到.

I don't know how to access redux dispatch in useFetching. I tried it with useReducer effect, but the sagas missed the action.

推荐答案

您需要将绑定的动作创建者或对 dispatch 的引用传递给您的钩子.这些将来自一个连接的组件,就像你通常使用 React-Redux 一样:

You would need to pass either bound action creators or a reference to dispatch to your hook. These would come from a connected component, same as you would normally use React-Redux:

function MyComponent(props) {
    useFetching(props.fetchSomething);

    return <div>Doing some fetching!</div>
}

const mapDispatch = {
    fetchSomething
};

export default connect(null, mapDispatch)(MyComponent);

然后钩子应该调用效果中的绑定动作创建者,这将相应地分派动作.

The hook should then call the bound action creator in the effect, which will dispatch the action accordingly.

另外,请注意您当前的钩子将在组件重新渲染时每次重新运行效果,而不仅仅是第一次.您需要像这样修改钩子:

Also, note that your current hook will re-run the effect every time the component is re-rendered, rather than just the first time. You'd need to modify the hook like this:

const useFetching = someFetchActionCreator => {
  useEffect( () => {
    someFetchActionCreator();
  }, [])
}

这篇关于反应钩子:从 useEffect 分派动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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