我将 ReactJS 与 Redux 一起使用,并且在 redux 更新时遇到了问题。
在一个组件中,我有以下内容:
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { State } from "state/State";
import { FormActions } from "state/form/actions";
import { StateToProps, DispatchToProps, DialogMetaComponent } from "./types";
import hasResponseId from "utils/hasResponseId";
import PrintDialog, { COMMAND_RESPONSE_ID } from "./PrintDialog";
const mapDispatchToProps = (
dispatch: Dispatch,
{ metaComponent }: { metaComponent: DialogMetaComponent },
): DispatchToProps => ({
onCleanUpCancel: () => {
const { cancelCommands }: DialogMetaComponent = metaComponent;
if (
!cancelCommands ||
(Array.isArray(cancelCommands) && !cancelCommands.length)
) {
return;
}
cancelCommands.map((command) =>
dispatch(
FormActions.removeCommand({
id: command,
}),
),
);
},
});
export default connect(mapStateToProps, mapDispatchToProps)(PrintDialog);
那个行动:
export interface FormCommand {
id: string;
forResponseId?: string;
params?: {
[key: string]: any;
};
[key: string]: any;
}
export const FormActions = {
removeCommand: (command: FormCommand) =>
action(FormActionTypes.REMOVE_COMMAND, command),
}
这是对应的reducer:
case FormActionTypes.REMOVE_COMMAND:
{
const commands = state.commands.filter(
(command: FormCommand) =>
!command.forResponseId ||
!command.forResponseId.includes(action.payload.id),
);
return {
...state,
commands: [...commands],
};
}
大多数情况下,它会正确删除命令。但有时 redux 会说:状态是平等的。并且不会删除任何命令。
通常我会期望:
FormActions.removeCommand({
id: command,
})
总是创建一个新对象(带有一个新的引用)。
你有想法吗 ?