我目前在通过redux向数组添加/减少数组时遇到问题。只是为了确保我的redux状态起作用,我将值硬编码并在每次按下按钮时触发。
有效的代码:
import * as actionType from '../actions/ActionType';
const counterReducer = (state = [], action) => {
let newState = [];
switch (action.type) {
case actionType.ADD_FILTER:
if (!state.includes(action.payload)) {
return newState = ['test'];
}
return newState = ['test'];
default:
return state;
}
};
export default counterReducer;
不会触发重新提交的代码:
import * as actionType from '../actions/ActionType';
const counterReducer = (state = [], action) => {
let newState = [];
switch (action.type) {
case actionType.ADD_FILTER:
if (!state.includes(action.payload)) {
const current = state;
current.push(action.payload);
return newState = current;
}
return newState = state;
default:
return state;
}
};
export default counterReducer;
但是redux存储更新了吗?帮助吗?
答案 0 :(得分:1)
无效的代码,原因是您正在改变状态(在引用了旧状态的数组上使用push方法),因为您再次传递了,redux不会注册为更改旧状态的参考。阅读克隆数组和切片方法。
const current =state.slice();
current.push(action.payload)
return current
现在您有了正确的克隆,返回该数组。那将触发重新渲染。
第一种情况也是可行的,因为您总是在创建一个新数组及其引用。