2017-04-23 125 views
1

Immutable.js的文檔不足以說明如何在React.js中使用setState正確更改狀態。使用React.js中的Immutable.js更改狀態

我有以下功能:

createComment(comment) { 

    const comments = Immutable.fromJS(this.state.comments); 
    var tempList = comments.concat({ 
     text: comment, 
     isAdmin: false 
    }); 
    this.setState({ comments: tempList.toJS() }); 

} 

它的工作,但問題是,數據不再是一成不變的,當你做到這一點,這違背了使用Immutable.js的目的,但事情是不能將不可變對象傳遞給setState函數。那麼我們應該怎麼做到這一點呢?

我知道數據是不再一成不變的,因爲我得到的錯誤:

comment.get is not a function 

回答

0

你應該閱讀本指南:Immutable as React state。您無需致電.toJS()

這是完全正常:

const comments = Immutable.fromJS(this.state.comments); 
var tempList = comments.concat({ 
    text: comment, 
    isAdmin: false 
}); 
this.setState({ comments: tempList }); 
+0

注意狀態必須是純JS對象,而不是一個不可改變的集合,因爲陣營的API的setState預計對象文本,將其合併(Object.assign)與以前的狀態。 – amd

+0

是'this.setState({comments:tempList})';正在工作,但'this.setState(tempList);'不工作,因爲它收到一個不可變列表。在github上的例子他們不使用'.toJS()'。 –

+0

註釋是一個不可變的對象。它不可能工作。 – amd