reactjs - 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 是复选框用于更新与所有可用过滤器相比的活动过滤器的方法。
解决方案
你肯定是在变异状态:
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 中生成新状态,还是在调度操作之前。
推荐阅读
- javascript - 如何使用 POST 值更新我的数据表。ASP.NET
- cucumber - 在黄瓜数据表的步骤定义末尾放置一个冒号 (:) 是一个好习惯吗?
- string - 如何在 Julia 中使用零填充格式化整数?
- python - 当我想将 pygame 1.9.x 安装到 python 3 时发生错误
- javascript - Node.js axios 无错误提示程序停止运行
- javascript - Vue.js 组件嵌入到另一个组件时不会出现
- excel - 工作表和 VBA 中的 INDEX/MATCH 之间的区别
- reactjs - 超过 1 次测试时反应 Jest 测试警告
- android - AudioPlaybackCapture API 的策略不起作用
- python - 从 Python 中可调用的字符串创建动态函数?