【问题标题】:Refactor from mapstatetoprops to hooks in React从 mapstatetoprops 重构为 React 中的钩子
【发布时间】:2021-03-03 10:54:58
【问题描述】:

我在重构使用类组件的 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 感到有些困惑。你能分享一下它是如何或在哪里被调用的吗?

标签: reactjs react-redux


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 2019-11-08
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多