reactjs – 使用React将状态值递增1
发布时间:2020-12-15 20:46:28 所属栏目:百科 来源:网络整理
导读:在React中,我试图使按钮增加存储在状态中的值. 但是,使用下面的代码函数时,我的值在使用handleClick时设置为undefined或NaN. class QuestionList extends React.Component { constructor(props) { super(props); this.state = {value: 0}; // This binding i
在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) } 你能告诉我为什么会这样吗?根据这里的文档,它应该是正确的:
因为您正在使用handleClick函数不正确.这里:
handleClick = (prevState) => { .... } prevState将是一个传递给handleClick函数的事件对象,你需要使用带有setState的prevState,如下所示: handleClick = () => { this.setState(prevState => { return {count: prevState.count + 1} }) } 另一个问题是,setState是异步的,所以console.log(this.state.value)不会打印更新的状态值,需要使用setState的回调函数. 查看有关async behaviour of 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') ); <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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |