我想在react.js中实现单向绑定。
我有 chatHistory 变量:
var chatHistory = [{ Author: "Daniel Lo Nigro", Text: "Hello ReactJS.NET World!" },
{ Author: "Pete Hunt", Text: "This is one comment" },
{ Author: "Jordan Walke", Text: "This is *another* comment" }];
如果 chatHistory 变量发生变化,我想做出更新 DOM 的反应。
这是我的代码:
var converter = new Showdown.converter();
var Comment = React.createClass({
displayName: 'Comment',
render: function () {
var rawMarkup = converter.makeHtml(this.props.children.toString());
return (
React.DOM.div({ className: "comment" },
React.DOM.h2({ className: "commentAuthor" },
this.props.author
),
React.DOM.span({ dangerouslySetInnerHTML: { __html: rawMarkup } })
)
);
}
});
var CommentList = React.createClass({
displayName: 'CommentList',
render: function () {
var commentNodes = chatHistory.map(function (comment) {
return Comment({ author: comment.Author }, comment.Text);
});
return (
React.DOM.div({ className: "commentList" },
commentNodes
)
);
}
});
var CommentBox = React.createClass({
displayName: 'CommentBox',
render: function () {
return (
React.DOM.div({ className: "commentBox" },
React.DOM.h1(null, "Comments"),
CommentList()
)
);
}
});
React.renderComponent(CommentBox(),document.getElementById('content'));
仅在调用React.renderComponent(CommentBox(),document.getElementById('content'));
后才更改DOM,而不是通过单向绑定自动更改。
当 chatHistory 变量发生变化时,如何强制对刷新DOM做出反应?
答案 0 :(得分:2)
React有两种方法可以强制重新渲染 - forceUpdate()和setState();
setState可能是你想要使用的方法。
http://facebook.github.io/react/docs/component-api.html#setstate
React教程的这一部分解释了使用setState很好地通过ajax动态更新模型数据
http://facebook.github.io/react/docs/tutorial.html#fetching-from-the-server