2017-04-23 75 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