我想用Redux存储处理一个简单的布尔值。但是,此值导致在每个调度事件上均未定义。你们中有人看到原因吗?

我有以下设置:

reducer.js

const initialState = {
    canSwipe: true
};

export default function rootReducer(state = initialState, action) {
    switch (action.type) {
        case CAN_SWIPE: {
        console.log(action.payload.canSwipe) // This logs true or false - works!
        return action.payload.canSwipe
        }
        default:
            return state;
    }
}


actions.js

export const setSwipeState = canSwipe => ({ type: CAN_SWIPE, payload: { canSwipe } });


调度组件

function MapOverlay({setSwipeState}) {
    const zoom = 5;
    return (
        <Map
            onMovestart={() => setSwipeState(false)}
            onMoveend={() => setSwipeState(true)}
        >
            {...}
        </Map>
    )
}

export default connect(null, {setSwipeState})(MapOverlay);

最佳答案

reducer应该返回必须符合您的初始状态的数据:

const initialState = {
    canSwipe: true
};


因此,您需要更改减速器以遵守以下结构:

switch (action.type) {
        case CAN_SWIPE: {
        console.log(action.payload.canSwipe) // This logs true or false - works!
        return {canSwipe: action.payload.canSwipe}
        }

07-24 15:12