问题描述
在我的本机redux应用程序的mapStatetoProps
函数中,我需要结合state中的某些元素和使用reselect创建的选择器。
基本上,我有两件事:
const mapStatetoProps = (state) => ({
storedUserName: state.user.name,isUserLoggedIn: state.user.isLoggedIn,})
const mapStatetoProps = createStructuredSelector({
email: emailSelector,userData: userDataSelector
});
我需要一种将这两种方式结合在一起的方法,以便我只有一个mapStatetoProps
函数才能拥有全部4个道具。我只是不知道该怎么做。请帮忙。
解决方法
尝试此代码
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状态作为参数并返回一些数据的函数
重新选择:在计算派生数据/对选择器选择的数据进行计算/应用过滤器时,将使用重新选择库。重新选择是有效的。
注意:当您只需要从状态获取数据而无需任何计算和过滤器时,就不需要重新解析
,选择器是将Redux状态作为参数并返回一些数据以传递给组件的函数,如下所示:
// selector
const getDataType = state => state.editor.dataType;
您可以做的是
import { getDataType } from '../selectors'
const mapStateToProps = (state) => ({
storedUserName: state.user.name,dataType: getDataType(state) <-- selector -->
})