javascript - 将 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:以上代码仅用于演示,共享组件和父组件实际存在于不同的项目中。
感谢您的所有投入。
解决方案
你可以dispatch
像任何其他函数一样将函数传递给 different components
,如果你可以使用useDispatch
钩子并且如果不是possible
出于任何原因,最好将dispatch
函数作为道具传递是正确的方法
推荐阅读
- svelte - Sveltestrap 下拉选择值
- schemacrawler - 无法在 schemacrawler 中写入输出文件
- python - 如何使用 BERT 模型和 TensorflowLite 预测(分类)用户句子
- java - Paypal Native Checkout Button 不断加载,然后在 Android 上消失
- javascript - 如何在html中循环javascript变量和数组?
- pytorch - RuntimeError:无法分配字节对象!在torch.save
- lua - A* 启发式寻路无法正常工作
- r - 当一行的两列的值相同但在另一行的相反列中时,用于删除重复项的 r 代码是什么
- android - 将文件提供程序添加到清单时,Android 应用程序无法启动
- javascript - 从 React 直接上传到谷歌云存储(图像/文档)