首页 > 解决方案 > 将 Redux useDispatch hook 中的“dispatch”函数作为 prop 传递给子组件

问题描述

我需要从使用它的项目中创建一个需要使用状态的共享组件(使用调度函数来操作 redux 存储中的状态),并且使用该组件的项目使用 Redux 作为它们的状态管理系统。所以我的问题是让父组件(使用此共享组件的项目)中的 useDispatch Hook 中的“调度”功能传递给此共享组件,作为在此组件内使用它的道具,这是一种正确的实现方式吗?会不会有什么副作用?

这是一个简单的代码片段来演示上面提到的实现:

父组件:

import React from 'react'
import { useDispatch} from 'react-redux'
import ChildComponent from "./ChildComponent"

export const ParentComponent = () => {
  const dispatch = useDispatch()
  return <div><ChildComponent dispatch={dispatch}/></div>
}

子组件(共享组件):

import React from 'react'

export const ChildComponent= ({dispatch}) => {
  const eventHandler = () => dispatch(action())

  return ...
}

P/S:以上代码仅用于演示,共享组件和父组件实际存在于不同的项目中。

感谢您的所有投入。

标签: javascriptreactjsredux

解决方案


你可以dispatch像任何其他函数一样将函数传递给 different components,如果你可以使用useDispatch钩子并且如果不是possible出于任何原因,最好将dispatch函数作为道具传递是正确的方法


推荐阅读