reactjs - 从 mapstatetoprops 重构为 React 中的钩子
问题描述
我正在重构使用类组件的 React 遗留代码,并遇到了如下所示的 mapstatetoprops 函数:
const mapStateToProps = (state) => ({
getProductById: (id) => getProductById(state, id),
selectedOutletId: getSelectedOutletId(state),
});
而我想做的是将mapstatetoprops转换成钩子useSelector。所以,我遇到了转换的问题getProductById: (id) => getProductById(state, id)
,也就是说,在挂钩中我将它转换为
const productById =(id) =>useSelector((state)=>getProductById(state, id))
但它说
React Hook "useSelector" 在函数 "productById" 中被调用,它既不是 React 函数组件也不是自定义 React Hook 函数
解决方案
您可能需要不同的挂钩来转换getProductById: (id) => getProductById(state, id),
. 正如警告所暗示的,您不能useSelector
在函数中调用它,因为它是一个自定义钩子。您可能想尝试使用useStore
挂钩。
首先,您需要导入钩子。
import { useSelector, useStore } from 'react-redux'
.
然后,在您的 React 函数组件主体上。
function YourComponent(props) {
const store = useStore()
const selectedOutletId = useSelector(state => getSelectedOutletId(state))
const productById = (id) => getProductById(store.getState(), id)
}
推荐阅读
- flutter - PageView 和 AnimateToPage - 如何动态动画到 Page 到 Flutter 中的滚动位置
- amazon-web-services - AWS:“自定义域”卡在“更新”状态一整天
- android - [Koin]:在视图模型中传递构造函数接口总是得到消息“无法创建实例”与 Koin
- mysql - 在 MySQL 中按 3 列(JobId、StartTime、EndTime)分组连续天数
- php - PHP 在 EC2 上包含和要求
- python - 为什么将外键字段添加到模型后 URL 不起作用?
- flutter - 我想要 Flutter 应用程序中的 Microsoft 身份验证
- python-3.x - Django:'TypeError:'HttpResponseForbidden'对象不可调用
- netsuite - NetSuite:在字段值更新时实时调用 API
- laravel - Eloquent 模型 save() 内存不足