Javascript 示例计数器应用程序失败-React.js
我已经使用react.js编写了以下示例计数器应用程序Javascript 示例计数器应用程序失败-React.js,javascript,reactjs,Javascript,Reactjs,我已经使用react.js编写了以下示例计数器应用程序onClick触发handleAddOne但count的值永远不会增加 class Counter extends React.Component { constructor(props){ super(props); this.handleAddOne = this.handleAddOne.bind(this); this.state = { count :
onClick
触发handleAddOne
但count
的值永远不会增加
class Counter extends React.Component {
constructor(props){
super(props);
this.handleAddOne = this.handleAddOne.bind(this);
this.state = {
count : 0
};
}
handleAddOne() {
console.log('handleAddOne');
this.state.count++;
}
render() {
return (
<div>
<h1>Count:{this.state.count}</h1>
<button onClick={this.handleAddOne}>+1</button>
</div>
);
}
}
ReactDOM.render(<Counter />, document.getElementById('app'));
类计数器扩展React.Component{
建造师(道具){
超级(道具);
this.handleAddOne=this.handleAddOne.bind(this);
此.state={
计数:0
};
}
handleAddOne(){
console.log('handleAddOne');
this.state.count++;
}
render(){
返回(
计数:{this.state.Count}
+1
);
}
}
ReactDOM.render(,document.getElementById('app'));
我建议您从
我建议您阅读更多关于
Reactjs
的信息
在react中,state是一个不可变的对象,这意味着您应该只使用setstse函数而不是直接设置state值
<button onClick={()=>{this.setState({count:this.state.count++})
}}>
+1
</button>
{this.setState({count:this.state.count++})
}}>
+1
在react中,state是一个不可变的对象,这意味着您应该只使用setstse函数而不是直接设置state值
<button onClick={()=>{this.setState({count:this.state.count++})
}}>
+1
</button>
{this.setState({count:this.state.count++})
}}>
+1
正如其他答案所建议的那样,您应该使用setState
触发状态更改并重新启动
但是,在使用prevState
时,还建议您使用setState
handleAddOne() {
console.log('handleAddOne');
this.setState(prevState=>({
count: prevState.count+1
}));
}
文档:正如其他答案所建议的,您应该使用
setState
触发状态更改并重新启动
但是,在使用prevState
时,还建议您使用setState
handleAddOne() {
console.log('handleAddOne');
this.setState(prevState=>({
count: prevState.count+1
}));
}
文档:状态可以是不可变的。但是变量是可变的,如果我没有错的话。为什么只
this.state.count++
不将workCount作为状态的内部对象。所以这也是不可变的。状态可以是不可变的。但是变量是可变的,如果我没有错的话。为什么只this.state.count++
不将workCount作为状态的内部对象。这也是不可变的,因为state
不是一个普通的javascript概念。React使用基于推送的状态更新系统,需要您使用setState
触发重新渲染,因为state
不是一个正常的javascript概念。React使用基于推送的状态更新系统,需要您使用setState
触发重新渲染