当前,我有以下的reducer switch语句。它所做的只是切换补充工具栏的状态,因此首先显示,然后隐藏,然后显示。这简单。
switch(action.type) {
case 'SIDEBAR_DISPLAY_TOGGLE':
return {
...state,
Sidebar : {
...state.Sidebar,
Display : !state.Sidebar.Display
}
}
default:
return state;
}
人们可以键入来搜索帐户。我正在尝试设置Redux,以便在用户键入时将其保存到Redux全局状态,并且可以从另一个组件中提取它。我已经为其设置了reducer代码,但是我不知道如何从该组件中将哪些用户类型输入到该reducer中?
function reducer(state = initialState, action) {
switch(action.type) {
case 'ACCOUNT_SEARCH':
return {
...state,
AccountNumberSearch : {
...state.AccountNumberSearch,
AccountNumber : ''
}
}
default:
return state;
}
}
}
答案 0 :(得分:0)
动作只是一个对象,该对象具有名为type
的字符串值。该对象上的所有其他属性也将被传递,因此您可以使用它来传递键入的文本。
如果您使用函数来创建动作,则类似于:
export function accountNumberSearch(accountNumber) {
return { type: 'ACCOUNT_SEARCH', accountNumber };
}
然后在化简器中,您可以将状态中的值分配给action.accountNumber。
AccountNumberSearch : {
...state.AccountNumberSearch,
AccountNumber : action.accountNumber,
}
然后,您可以像平常一样将状态映射到道具(就像您在侧边栏切换中所做的那样)。
此外,除此之外,您还应该考虑使用combineReducers
-Docs对化径器进行模块化
这将比您的操作方式容易得多。
编辑:处理更改
首先,您希望将搜索框的输入字段连接到onChange侦听器。如果您像onChange={this.onSearchChange}
这样操作,则可以在函数中从event
获取值:
onSearchChange = event => {
this.props.AccountNumberSearch(event.target.value);
}
然后在mapDispatchToProps
中,您将操作+传递的值发送给调度人员:
const mapDispatchToProps = dispatch => {
return {
AccountNumberSearch: AccountNumber => dispatch(importedActions.AccountNumberSearch(AccountNumber)),
}
}
然后,在要接收该值的组件中,将redux状态映射到props,例如:
const mapStateToProps = state => {
return {
AccountNumber: state.AccountNumberSearch.AccountNumber,
}
}
然后,您可以通过调用this.props.AccountNumber
在渲染函数中访问该值。
如果在此值更改时需要执行某些操作,则可以随时收听componentDidUpdate
,并将该值与旧值进行比较-如果更改,则调用您需要执行的任何功能。