简体   繁体   English

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

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

In my react-native redux app, in my mapStateToProps function, I need to combine some elements from state and some selectors created using reselect.在我的 react-native redux 应用程序中,在我的mapStateToProps函数中,我需要组合来自 state 的一些元素和一些使用 reselect 创建的选择器。

Basically, I have two things:基本上,我有两件事:

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

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

I need a way to combine these two so that I have all 4 props with only one mapStateToProps function.我需要一种方法将这两者结合起来,以便我拥有所有 4 个道具,并且只有一个mapStateToProps函数。 I just don't know how to do this.我只是不知道该怎么做。 Please help.请帮忙。

Try this code试试这个代码

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
})

Selectors : Selectors are functions that take Redux state as an argument and return some data选择器:选择器是将 Redux 状态作为参数并返回一些数据的函数

reselect : You will use the reselect library when you compute derived data/make calculations/apply filters on data selected by selector. reselect :当您计算派生数据/进行计算/对选择器选择的数据应用过滤器时,您将使用重新选择库。 Reselect is effcient.重新选择是有效的。

Note : You do not need reslsect when you have to just get data from state without any calculations and filters注意:当您只需要从 state 获取数据而不需要任何计算和过滤器时,您不需要 reslsect

Selectors are functions that take Redux state as an argument and return some data to pass to the component, like this:选择器是将 Redux 状态作为参数并返回一些数据以传递给组件的函数,如下所示:

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

You can do is你可以做的是

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