繁体   English   中英

React Native Redux 一起使用状态道具和选择器

[英]React Native Redux Using state props and selectors together

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

基本上,我有两件事:

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

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

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

试试这个代码

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 状态作为参数并返回一些数据的函数

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

注意:当您只需要从 state 获取数据而不需要任何计算和过滤器时,您不需要 reslsect

选择器是将 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 -->
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM