我正在关注来自this tutorial的React.js Facebook。 我在这里添加了一个更像LikeButton的组件:
var LikeButton = React.createClass({
getInitialState: function() {
return {liked: this.props.liked, id: this.props.id};
},
handleClick: function(event) {
// post to server using ajax here
this.setState({liked: !this.state.liked, id: this.prop.id});
},
render: function() {
var text = this.state.liked ? 'like' : 'unlike';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.
</p>
);
}});
然后我将组件放在注释块中:
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function (comment) {
return <div>
<Comment author={comment.author}>
{comment.content}</Comment><LikeButton liked={comment.liked} id={comment.id} / </div>;
});
最后,我使用CommentBox中的setInterval来使用轮询实时更新。
var CommentBox = React.createClass({
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
}
React.renderComponent(
<CommentBox url='comments.json' pollInterval={3000}/>,
document.getElementById('content')
);
当我点击时,LikeButton组件可以正确呈现,但是当使用setInterval时,在服务器端,我手动更改了注释的likes属性,但LikeButton组件无法正确呈现。 你知道如何解决这个问题吗? 非常感谢你。
答案 0 :(得分:0)
你必须在服务器端坚持你只是设置状态所以使用axios
handleClick: function(event) {
// post to server using ajax here
this.setState({liked: !this.state.liked, id: this.prop.id});
liked = this.state.liked;
id = this.prop.id;
axios.post('/YOUR_LIKE_UNLIKE_API_END_POINT', {
liked: liked,
id: id
}).catch(function (error) {
this.setState({liked: !this.state.liked, id: this.prop.id});
});
},