处理ReactJs中的状态变化

Handling state changes in ReactJs

本文关键字:状态 变化 ReactJs 处理      更新时间:2023-09-26

我试图用handleClick()函数实现3件事。切换buttonText为following或follow,切换"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

并使用它来设置动作中的state和follow_status。不要设置state然后立即调用它,因为它不是一个同步调用,可能会也可能不会及时完成。

    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
        }
      });
    }