繁体   English   中英

在ReactJs中处理状态更改

[英]Handling state changes in ReactJs

我正在尝试使用handleClick()函数实现3件事。 将buttonText切换为跟随还是跟随,切换“ active”类并处理FOLLOW动作。 我可能做错了。 由于某些原因,onClick事件对此没有任何影响。 有任何想法吗? 谢谢

class FollowButton extends React.Component {
​
  constructor() {
    super();
    this.state = {};
    this.state.following_state = true;
  }
​
  handleClick(event) {
    event.preventDefault();
    this.setState({following_state: !this.state.following_state});
​
    let follow_state = following_state;
    ProfilesDispatcher.dispatch({
      action: FOLLOW,
      follow_status: {
        following: follow_state
      }
    });
  }
​
  render() {
​
    let buttonText = this.state.following_state? "following" : "follow";
    let activeState = this.state.following_state? 'active': '';
​
    return (
      <button className={classnames(this.props.styles, this.props.activeState)} 
        onClick={this.handleClick.bind(this)}>{buttonText}</button>
    );
  }
}

正如@Felix King指出的那样,您正在使用未定义的变量following_state 您应该定义此变量

    const following_state = !this.state.following_state

并使用它在操作中同时设置状态和follow_status。 不要设置状态,然后立即调用它,因为它不是同步调用,并且可能会或可能不会及时完成。

    handleClick(event) {
      event.preventDefault();
      const following_state = !this.state.following_state

      this.setState({following_state}); // You can do this in ES6, as shorthand for {following_state: following_state}

      ProfilesDispatcher.dispatch({
        action: FOLLOW,
        follow_status: {
          following: following_state
        }
      });
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM