将 mapStateToProps 转换为钩子

时间:2021-07-20 21:09:32

标签: javascript reactjs typescript react-redux react-hooks

我是通过编码来反应(钩子)世界学习的新手。 我的问题与 MapStateToProps 相关,我需要将它转换为钩子,我被它的一部分困住了(在“currentItem”之前) 这是我的代码:

const mapStateToProps = (state) => ({
  sites: state.articles.sites,
  analysers: state.siteArticles.analysers,
  brokers: state.siteArticles.brokers,
  cameras: state.siteArticles.cameras,
  platforms: state.siteArticles.platforms,
  currentItem: {
    sites: state.selection.currentSite,
    cameras: state.selection.currentCamera,
    analysers: state.selection.currentAnalyser,
    platforms: state.selection.currentPlatform,
    brokers: state.selection.currentBroker,
  },
});

这就是我转换它的方式,我认为它可以,但不知道如何转换开头:

 const currentItem = {
    sites: useSelector((state) => state.selection.currentSite),
    cameras: useSelector((state) => state.selection.currentCamera),
    analysers: useSelector((state) => state.selection.currentAnalyser),
    platforms: useSelector((state) => state.selection.currentPlatform),
    brokers: useSelector((state) => state.selection.currentBroker),
  };

1 个答案:

答案 0 :(得分:2)

我猜你尝试并且应该做的是:

// Inside function component
const currentItem = useSelector((state) => ({
  sites: state.articles.sites,
  analysers: state.siteArticles.analysers,
  brokers: state.siteArticles.brokers,
  cameras: state.siteArticles.cameras,
  platforms: state.siteArticles.platforms,
  currentItem: {
    sites: state.selection.currentSite,
    cameras: state.selection.currentCamera,
    analysers: state.selection.currentAnalyser,
    platforms: state.selection.currentPlatform,
    brokers: state.selection.currentBroker,
  },
}));