2017-01-19 35 views
0

我試圖凍結我的對象內的鍵,以便我不會意外更新它們,因爲我使用React Native(0.34.0)和Redux,所以我需要使用純功能。反應本機Object.freeze不工作

然而,使用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; 
    } 
} 
+0

Object.freeze對我來說工作正常(在iOS上測試過)。你在測試什麼平臺?此外,請嘗試在文件頂部添加''strict strict'',以查看變異的凍結對象是否會引發錯誤 - 應該採用嚴格模式。 – jevakallio

回答

0

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

嚴格的模式不被默認啓用,因爲 Facebook有一些模塊是不符合嚴格的模式 包裝者也transpiles node_modules下的文件,所以任何庫沒有嚴格的書面模式會中斷。

我使用Babel的轉換嚴格插件來執行此操作,它對我來說工作正常。 https://babeljs.io/docs/plugins/transform-strict-mode/

請注意,如果您包含非嚴格模塊,它可能會中斷,或者Facebook將來會在ReactNative中包含非嚴格模塊。