首页 > 解决方案 > 从 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 函数

标签: reactjsreact-redux

解决方案


您可能需要不同的挂钩来转换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)
}

推荐阅读