在React中,我试图使按钮增加存储在状态中的值.但是,使用下面的代码函数时,我的值在使用handleClick时设置为undefined或NaN.
class QuestionList extends React.Component {
constructor(props) {
super(props);
this.state = {value: 0};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick = (prevState) => {
this.setState({value: prevState.value + 1});
console.log(this.state.value)
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我为什么会这样吗?它应该是正确的根据这里的文档:https: //facebook.github.io/react/docs/state-and-lifecycle.html
May*_*kla 23
因为您正在使用handleClick函数不正确.这里:
handleClick = (prevState) => { .... }
Run Code Online (Sandbox Code Playgroud)
prevState 将是一个传递给handleClick函数的事件对象,你需要使用带有setState的prevState,如下所示:
handleClick = () => {
this.setState(prevState => {
return {count: prevState.count + 1}
})
}
Run Code Online (Sandbox Code Playgroud)
另一个问题是,setState是异步的,因此console.log(this.state.value)不会打印更新的状态值,需要使用setState的回调函数.
检查有关setState的异步行为以及如何检查更新值的更多详细信息.
检查工作解决方案:
class App extends React.Component {
constructor(props){
super(props);
this.state={ count: 1}
}
onclick(type){
this.setState(prevState => {
return {count: type == 'add' ? prevState.count + 1: prevState.count - 1}
});
}
render() {
return (
<div>
Count: {this.state.count}
<br/>
<div style={{marginTop: '100px'}}/>
<input type='button' onClick={this.onclick.bind(this, 'add')} value='Inc'/>
<input type='button' onClick={this.onclick.bind(this, 'sub')} value='Dec'/>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='container'></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33127 次 |
| 最近记录: |