1

我正在关注本教程中的 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 时,我手动更改了评论的 like 属性,但 LikeButton 组件无法正确呈现。你知道如何解决这个问题吗?非常感谢。

4

1 回答 1

0

你必须在服务器端坚持你只是设置状态所以改变你的 handleClick 功能像这样使用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});
  });
},
于 2017-02-27T07:18:27.647 回答