React Redux-布尔值未定义

时间:2019-10-27 13:38:28

标签: javascript reactjs redux react-redux

我想用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);

1 个答案:

答案 0 :(得分:3)

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

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

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

{{1}}