处理ReactJs中的状态变化
Handling state changes in ReactJs
我试图用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
}
});
}
相关文章:
- React redux初始化功能,无论状态变化如何
- 检测Ionic中特定的应用程序状态变化
- ReactJS-这个状态中的数组在删除时被正确更新,但结果是't,直到以后的状态发生变化
- 消除淘汰中引导程序开关状态变化的歧义
- 反应组件交互和全局状态变化
- 根据单选按钮的状态变化使儿童内容出现/消失
- 观察angular ui路由器的状态变化
- 如何与Redux沟通React组件之间的UI状态变化
- html5事件监听器详细节点状态变化
- 角度/离子谷歌地图的状态变化
- ReactJS -检测状态变化的问题
- 处理ReactJs中的状态变化
- 按钮循环3个状态变化
- 每次状态变化时的离子运行函数
- FP:在没有实际状态变化的情况下反映状态
- ReactJS:如何测试状态变化
- 发生状态变化时不应用ng类
- 动态jQuery CSS具有三状态滚动背景位置根据状态变化
- 承诺后的角度状态变化
- 是否有管理事件的“量子状态变化”的有用模式?(特别是在JavaScript中)