参数“动作”和“动作”的类型不兼容

时间:2017-12-20 16:26:41

标签: reactjs typescript react-redux

我刚刚开始使用reactcript(v 2.6.1)的react redux,我一直在使用VS 2017样板上的一个小应用程序。在我的第五个视图中,我看到由于某种原因,我在创建操作时遇到问题。基本上在下面的代码中,这是一个非常简化的代码,如果我在Multiply动作中删除乘数,但是当我添加乘数时,它应该非常容易。我无法理解。

尝试简化和修复它,我发现它甚至没有使用下面的代码,这应该是相当直接的。

import { AppThunkAction } from "ClientApp/store";
import { Action, Reducer } from 'redux';
import { fetch, addTask } from 'domain-task';
import update from 'immutability-helper';

// The top-level state object
export interface CompoundState {
    value: number,
}

export interface AddAction  {
    type: 'ADD_ACTION',
    addend:number
}

export interface MultiplyAction {
    type: 'MULTIPLY_ACTION',
    multiplier:number
}

type KnownAction = AddAction | MultiplyAction
export const actionCreators = {
    add: (addend): AppThunkAction<AddAction> => (dispatch, getState) => {
        dispatch({ type: 'ADD_ACTION', addend: addend })
    },
    multiply: (multiplier): AppThunkAction<MultiplyAction> => (dispatch, getState) => {
        dispatch({ type: 'MULTIPLY_ACTION', multiplier: multiplier })
    },
}

const unloadedState: CompoundState =
{
    value: 0,
};
export const reducer: Reducer<CompoundState> = (state: CompoundState, action: KnownAction) => {

    switch (action.type) {
        case 'ADD_ACTION':
            return update(state, {
                value: {
                    $set: state.value + action.addend
                }
            });
        case 'MULTIPLY_ACTION':
            return update(state, {
                value: {
                    $set: state.value * action.multiplier
                }
            });

    }
    return state || unloadedState;
};

您怎么看?

1 个答案:

答案 0 :(得分:2)

export const reducer: Reducer<CompoundState> = (state: CompoundState, incomingAction: Action) => {
    const action = incomingAction as KnownAction;
    switch (action.type) {
        case 'ADD_ACTION':
            return update(state, {
                value: {
                    $set: state.value +1
                }
            });
        case 'MULTIPLY_ACTION':
            return update(state, {
                value: {
                    $set: state.value * 2
                }
            });

    }
    return state || unloadedState;
};

希望它可以帮助某人。