Redux - pass ownProps argument to selector

◇◆丶佛笑我妖孽 提交于 2019-12-06 06:35:12

问题


I cannot pass variable ownProps from mapStateToProps to selector. My selector:

export const nameSelector = createSelector(
    [
        state => state.element.get('name')
    ],
    (name) => !name.trim()
);

const mapStateToProps = (state, ownProps) => ({
    disabledAfterSave: nameSelector(state)
});

And I need to have a selector:

export const nameSelector = createSelector(
        [
            state => state.element.get('name')
        ],
        (name, ownProps) => !name.trim() && ownProps.showMessage
    );

const mapStateToProps = (state, ownProps) => ({
    disabledAfterSave: nameSelector(state, ownProps)
});

But now I get an error: ReferenceError: ownProps is not defined.

When I tried to pass it like below:

export const nameSelector = (ownProps) => createSelector(
        [
            state => state.element.get('name')
        ],
        (name) => !name.trim() && ownProps.showMessage
    );

the returned type is not bool but [Function selector]. How can I pass this argument to my selector?


回答1:


Here's how to fix your selector and its usage:

export const nameSelector = createSelector(
  [
    state => state.element.get('name'),
    (state, ownProps) => ownProps.showMessage
  ],
  (name, showMessage) => !name.trim() && ownProps.showMessage
)

const mapStateToProps = (state, ownProps) => ({
  disabledAfterSave: nameSelector(state, ownProps)
})

Here's a generic working example, in order to illustrate how you can pass props down to the selector:

const createSelector = Reselect.createSelector

// Selector: Get Active Users
const getUsers = createSelector([state => state.users], users => users.filter(u => u.active))

// Selector: Get Active Users by Country
// Here you can check how I pass the country prop
const getUsersByCountry = createSelector([getUsers, (state, props) => props.country],
 (users, country) => users.filter(u => u.country === country))

// The state
const state = {
  users: [
    { id: 1, name: 'Jordan', country: 'Bulgaria', active: true},
    { id: 2, name: 'Nadezhda', country: 'Bulgaria', active: true},
    { id: 3, name: 'Hristo', country: 'Bulgaria', active: false},
    { id: 4, name: 'Bobby', country: 'England', active: true},
    { id: 5, name: 'Kaloyan', country: 'Germany', active: true},
  ]
}

// Testing
console.log(getUsers(state))
console.log(getUsersByCountry(state, { country: 'Bulgaria' }))
<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/3.0.1/reselect.min.js"></script>


来源:https://stackoverflow.com/questions/50562373/redux-pass-ownprops-argument-to-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!