React Native Object.freeze无效

时间:2017-01-19 13:09:20

标签: javascript react-native redux purely-functional

我试图冻结对象内部的密钥,以便我不会意外更新它们,因为我使用的是React Native(0.34.0)和Redux,所以我需要使用纯粹的功能。

然而,使用deepFreeze npm包,以及尝试Object.freeze(...)它仍然让我在以下代码上改变我的键,任何帮助都将不胜感激!

var Immutable = require('immutable');
var deepFreeze = require('deep-freeze');

import * as types from '../actions/actionTypes';

const initialState = {
    customBackgroundColour: '#f7f7f7'
};

export default function backgroundColour(state = initialState, action = {}) {

switch (action.type) {
    case types.SET_BACKGROUND_COLOUR:

        deepFreeze(state);
        deepFreeze(action);

        console.log(Object.isFrozen(state)); // true
        console.log(state.customBackgroundColour); // #f7f7f7

        state.customBackgroundColour = 'red';
        console.log(state.customBackgroundColour); // red

        return {
            ...state,
            customBackgroundColour: action.payload.colour
        };
    default:
        return state;
    }
}

1 个答案:

答案 0 :(得分:1)

请参阅https://github.com/facebook/react-native/issues/5316

默认情况下不启用严格模式,因为 facebook有一些模块不符合严格模式打包器也会转换node_modules下的文件,所以任何库都不是用严格模式编写的会破裂。

我正在使用Babel的transform strict插件来强制执行此操作,它对我来说很好。 https://babeljs.io/docs/plugins/transform-strict-mode/

请注意,如果您包含非严格模块可能会中断,或者Facebook将来会在ReactNative中包含非严格模块。