React Hooks:useEffect的分派动作 [英] React hooks: dispatch action from useEffect
问题描述
我的文件夹结构:
|--App
|--Components
|--PageA.js
|--PageB.js
|--PageC.js
|--common-effects
|--useFetching.js
我正在使用react hooks 重构代码以从API提取数据. 我想从 saga 中间件拦截的 useFetching.js 中的 useEffect 调度一个动作.仅当安装了组件( PageA , PageB , PageC )时,才分派该动作.
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.
我正在使用 redux , react-redux 和 redux-saga .
PageA.js :
function(props) {
useFetching(actionParams)
//....//
}
PageB 和 PageC 组件的相似代码.
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
效果,但是sagas错过了动作.
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();
}, [])
}
这篇关于React Hooks:useEffect的分派动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!