为什么我的州没有定义?

时间:2016-10-20 09:14:10

标签: javascript ecmascript-6

下面是es5语法

function customMsg(state, action) {
     state = state || {};
    return $.extend({}, state, {
       isFetching: false,
        didInvalidate: false,
        checkStatus: checkStatus(state.checkStatus, action)
     });
}

function checkStatus(state, action) {
    state = state || {
        isFetching: false,
        didInvalidate: false,  
        type: "room"
    };
        return state;
    }
}

下面是es6语法

const initialStae = {
    isFetching: false,
    didInvalidate: false,
    checkStatus: checkStatus(state.checkStatus, action)
}

function customMsg(state = initialStae, action) {
    return state;
}

function checkStatus(state, action) {
    state = state || {
        isFetching: false,
        didInvalidate: false,  
        type: "room"
    };

    return state;
}

为什么我的第7行会从es6中显示“状态未定义”?

customMsgReducer.js:36Uncaught ReferenceError: state is not defined(…)

1 个答案:

答案 0 :(得分:1)

在ES5中,您定义state = state || {};,然后访问state.checkStatus。因此它的工作。

function customMsg(state, action) {
     state = state || {};
    return $.extend({}, state, {
       isFetching: false,
        didInvalidate: false,
        checkStatus: checkStatus(state.checkStatus, action)
     });
}

但是在ES6中,您访问state.checkStatus而未在此处定义state undefined。因此,访问checkStatus的{​​{1}}会导致错误。

相关问题