【问题标题】:React Native Redux Using state props and selectors togetherReact Native Redux 一起使用 state props 和 selectors
【发布时间】:2020-10-23 05:31:42
【问题描述】:

在我的 react-native redux 应用程序中,在我的 mapStateToProps 函数中,我需要组合状态中的一些元素和使用重新选择创建的一些选择器。

基本上,我有两件事:

const mapStateToProps = (state) => ({
    storedUserName: state.user.name,
    isUserLoggedIn: state.user.isLoggedIn,
})

const mapStateToProps = createStructuredSelector({
  email: emailSelector,
  userData: userDataSelector
});

我需要一种将这两者结合起来的方法,这样我就拥有所有 4 个道具和一个 mapStateToProps 函数。我只是不知道该怎么做。请帮忙。

【问题讨论】:

    标签: reactjs react-native redux react-redux reselect


    【解决方案1】:

    试试这个代码

    import { createSelector } from 'reselect'
    
    const emailSel = state => state.user.email
    const userDataSel = state => state.user
    
    const emailSelector = createSelector(
      emailSel,
      email => email // you can make calculations on input and return value
    ) 
    
    const userDataSelector = createSelector(
      userDataSel,
      userData => userData // you can make calculations on input and return value
    ) 
    
    const mapStateToProps = (state) => ({
        storedUserName: state.user.name,
        isUserLoggedIn: state.user.isLoggedIn,
        email: emailSelector,
        userData: userDataSelector
    })
    

    选择器:选择器是将 Redux 状态作为参数并返回一些数据的函数

    重新选择:当您计算派生数据/进行计算/对选择器选择的数据应用过滤器时,您将使用重新选择库。重新选择是有效的。

    注意:当您必须从状态中获取数据而无需任何计算和过滤器时,您不需要 reslsect

    【讨论】:

      【解决方案2】:

      选择器是将 Redux 状态作为参数并返回一些数据以传递给组件的函数,如下所示:

      // selector
      const getDataType = state => state.editor.dataType;
      

      你可以做的是

      import { getDataType } from '../selectors'
      
      const mapStateToProps = (state) => ({
          storedUserName: state.user.name,
          isUserLoggedIn: state.user.isLoggedIn,
          
          dataType: getDataType(state) <-- selector -->
      })
      

      【讨论】:

      • 那么,我们不需要createStructuredSelector?
      • 不,除非您必须从状态中获取数据而不进行任何计算。
      猜你喜欢
      • 2018-05-04
      • 2016-10-17
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 2018-12-04
      • 1970-01-01
      相关资源
      最近更新 更多