我做了一个redux状态和reducer,它从状态数组中删除了一些值。
这是动作文件。
import {FFAction} from "utils/reducer-helper";
interface RemovePalettePayload {
palette?: any;
}
export const PaletteRemove = new FFAction<RemovePalettePayload>("PALETTE_REMOVE");
// Action creators
export const PaletteActionCreators = {
removePalette: (palette: any) => {
return PaletteRemove.makeAction({ palette });
}
};
和减速器
import { ReducerHelper } from "utils/reducer-helper";
import {
PaletteRemove
} from "redux/actions/palette";
interface PalettePayload {
id: string,
color: string
}
export interface PaletteState {
palette?: PalettePayload[];
}
export const initialState: PaletteState = {
palette: []
};
const PaletteReducerHelper = new ReducerHelper(initialState)
.registerHandler(PaletteRemove, (state, type, payload, error) => {
let oldPalette = payload.palette;
let newPaletteData = _.filter(state.palette, (s) => {
return !_.find(oldPalette, { id: s.id});
});
let newPalette:PaletteState = {
palette: newPaletteData
};
console.log(state);
console.log(_.assign({}, newPalette));
return _.assign({}, newPalette);
});
export const paletteReducer = PaletteReducerHelper.reducer;
我用lodash进行数组和对象操作。
如你在reducer函数中所见,我想返回一个新状态,该状态不包含来自payload.palette的ids
。
我什至打印了当前状态和更新值。
console.log(state);
console.log(_.assign({}, newPalette));
此打印的估算结果。
{
palette: [{id: "1", color: "white"}]
}
{
palette: []
}
但是在我的react组件中,如果我在componentWillReceiveProps()函数中看到nextProps的还原状态,则会显示
{
palette: [{id: "1", color: "white"}]
}
这是怎么了?
当然,此PaletteActionCreators中的其他减速器也可以工作。