gpt4 book ai didi

Redux - 将 ownProps 参数传递给选择器

转载 作者:行者123 更新时间:2023-12-01 00:18:32 24 4
gpt4 key购买 nike

我无法传递变量 ownProps来自 mapStateToProps到选择器。我的选择器:

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

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

我需要有一个选择器:
export const nameSelector = createSelector(
[
state => state.element.get('name')
],
(name, ownProps) => !name.trim() && ownProps.showMessage
);

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

但现在我收到一个错误: ReferenceError: ownProps is not defined .

当我尝试像下面这样传递它时:
export const nameSelector = (ownProps) => createSelector(
[
state => state.element.get('name')
],
(name) => !name.trim() && ownProps.showMessage
);

返回的类型不是 bool 而是 [Function selector] .
如何将此参数传递给我的选择器?

最佳答案

以下是修复选择器及其用法的方法 :

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

这是一个通用的工作示例,以说明如何将 Prop 向下传递给选择器 :

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>

关于Redux - 将 ownProps 参数传递给选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50562373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com