首页 > 解决方案 > Redux Dom 不刷新

问题描述

我正在更新我的 redux 状态,并且状态似乎没有发生变化,但是 DOM 仍然没有刷新。

//update filters for events
setFilters = (name) => async () => {
const {onSetActiveEventTypes, authUser} = this.props;

let array = this.props.activeEventTypes
let index = array.indexOf(name);

if (index > -1) {
  array.splice(index, 1);
}else {
  array.push(name)
}

await Promise.resolve(onSetActiveEventTypes(array));
}


render() {
return <Accordion title="Filters" collapsed>
      {
        (this.props.eventTypes && this.props.activeEventTypes ?
          <EventFilter eventTypes={this.props.eventTypes} activeEventTypes={this.props.activeEventTypes} action={this.setFilters}/>
         : '')
      }
    </Accordion>
}

const mapStateToProps = (state) => ({
eventTypes: state.eventsState.eventTypes,
activeEventTypes: state.eventsState.activeEventTypes
});

const mapDispatchToProps = (dispatch) => ({
onSetEventTypes: (eventTypes) => dispatch({ type: 'EVENT_TYPES_SET', 
eventTypes }),
onSetActiveEventTypes: (activeEventTypes) => dispatch({ type: 
'ACTIVE_EVENT_TYPES_SET', activeEventTypes })
});

const authCondition = (authUser) => !!authUser;

export default compose(
withAuthorization(authCondition),
connect(mapStateToProps, mapDispatchToProps)
)(DashboardPage);

我已将代码放在上面的组件中,它应该是调试所需的全部内容。我将减速机放在下面

const applySetEventTypes = (state, action) => ({
...state,
eventTypes: action.eventTypes
});

const applySetActiveEventTypes = (state, action) => ({
...state,
activeEventTypes: action.activeEventTypes
});

function eventsReducer(state = INITIAL_STATE, action) {
switch(action.type) {
case 'EVENT_TYPES_SET' : {
  return applySetEventTypes(state, action);
}
case 'ACTIVE_EVENT_TYPES_SET' : {
  return applySetActiveEventTypes(state, action);
}
default : return state;
}
}

export default eventsReducer;

以上是我的 reducer,我认为我正在遵循正确的模式来管理 redux 状态和保持不变性。我错过了什么?

setFilters 是复选框用于更新与所有可用过滤器相比的活动过滤器的方法。

标签: reactjsreduxreact-redux

解决方案


肯定是在变异状态:

const {onSetActiveEventTypes, authUser} = this.props;

let array = this.props.activeEventTypes
let index = array.indexOf(name);

if (index > -1) {
  array.splice(index, 1);
}else {
  array.push(name)
}

这会改变您从状态中获得的现有数组,然后您正在调度一个将相同数组放回状态的操作。所以,你们都是 A) 一直重复使用同一个数组,并且 B) 每次都改变那个数组。

Redux 文档中不可变更新模式页面中描述的方法适用于您创建新状态值的任何地方,无论您是基于几个小值在 reducer 中生成新状态,还是在调度操作之前。


推荐阅读