2016-10-26 255 views
1

發起比方說,一些微妙的原因,我有以下反應過來狀態:變異字符串從陣營狀態

{ superGreeting: 'Hello!!!' } 

現在,假設我有這樣複雜的操作,基本上採取superGreeting串並工作就可以了,在結束替換特定位置上的字符。那麼新的狀態應該是:

{ superGreeting: 'Hullo!!!' } 

那麼,就不會有我的行動:

action = (index) => { 
    var { superGreeting: newGreeting } = this.state; 
    newGreeting[index] = 'u'; 
    this.setState({superGreeting: newGreeting}); 
} 

可惜的是,這種方法是行不通的,結尾是: TypeError: Cannot assign to read only property '1' of string 'Hello!!!',表示該行違規之一: newGreeting[index] = 'u'

我使用react.js,ES6,沒有redux,沒有mobx,沒有immutable.js。認爲這個問題是由於字符串仍然被相關/由即將到來的狀態使用,所以我認爲創建一個副本將工作(我試過newGreeting = newGreeting.toString(),'' + newGreeting,`$ {newGreeting}`,''.concat(newGreeting),沒有任何成功)。有任何想法嗎?

回答

3

JavaScript中的字符串是不可變的。您的例子可以下調至

(function(){ 
    "use strict"; 
    var str = 'Hullo!!!'; 
    str[1] = 'e'; 
})(); 

如果你想發生變異的字符串,你需要創建一個新的字符串,例如

(function(){ 
    "use strict"; 
    var str = 'Hullo!!!'; 
    str = str.slice(0, 1) + 'e' + str.slice(2); 
})(); 
1

字符串在JS是不可變的,但你可以把它變成一個數組,它的工作,然後再加入它一起回來..也有像substrreplace字符串函數它會返回一個新的字符串,如果這些都適用。

var split = superGreeting.split('') 
split[index] = 'u' 
var newGreeting = split.join('') 
1

這裏的問題與反應沒有任何關係。 JavaScript中的字符串是不可變的。

您可以創建以下輔助函數:

var replaceCharAt = function(str, index, c) { 
    return str.slice(0, index) + c + str.slice(index+1) 
} 

使

replaceCharAt('012', 1, 'x') === '0x2' 
+0

謝謝!我已經修正了這個例子。 – Eoin

+0

完美,謝謝! – loganfsmyth