React简单示例中点击按钮后点击数未增加的问题求助
React点击按钮次数不更新问题排查
我是React新手,正在编写一个简单示例,预期点击按钮时修改state以触发子组件重新渲染,同时更新点击次数,但点击数始终停留在0,恳请帮忙排查问题所在。
代码文件
index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <script type="text/babel" src="app.js"></script> <div id="root"></div>
app.js
var Home = React.createClass({ componentWillMount: function(){ this.btnText = "click Me"; this.commentData = "No comments till now"; this.clickNo = 0; }, render: function(){ return ( <div> <ButtonComponent buttonText={this.btnText} clickNumber={this.clickNo} handleclick={this.clickHandler} /> <CommentComponent commentText={this.commentData} /> </div> ) }, clickHandler: function(){ this.setState({clickNo: this.state.clickNo++}); } }); var ButtonComponent = React.createClass({ render: function(){ return ( <button onClick={this.props.handleClick}>{this.props.buttonText}{this.props.clickNumber}</button> ) } }); var CommentComponent = React.createClass({ render: function(){ return ( <p>{this.props.commentText}</p> ) } }) ReactDOM.render(<Home />, document.getElementById('root'));
结果展示

问题原因及修复方案
1. 未正确初始化React State
在React.createClass中,必须通过getInitialState方法初始化组件状态,而非在componentWillMount中直接给实例赋值属性。你当前把clickNo存在实例属性this.clickNo里,而非state中,导致setState无法触发视图更新,且render时读取的不是state值。
2. setState用法错误
- 直接修改
this.state(如this.state.clickNo++)违反React状态更新规则,必须通过setState更新。 - 后自增运算符
++会先返回原值再递增,导致更新值不正确;且未初始化state时this.state.clickNo为undefined,运算后会变成NaN。 - 推荐使用函数式
setState,基于前一次state计算新值,避免异步更新的竞态问题。
3. Props传递大小写不匹配
Home组件传递给ButtonComponent的事件回调是handleclick(小写c),但ButtonComponent中读取的是this.props.handleClick(大写C),导致点击事件未正确绑定,clickHandler根本没执行。
修复后的完整代码
app.js
var Home = React.createClass({ // 初始化state getInitialState: function(){ return { clickNo: 0 } }, componentWillMount: function(){ this.btnText = "click Me"; this.commentData = "No comments till now"; }, render: function(){ return ( <div> {/* 修正props名称为handleClick */} <ButtonComponent buttonText={this.btnText} clickNumber={this.state.clickNo} handleClick={this.clickHandler} /> <CommentComponent commentText={this.commentData} /> </div> ) }, // 正确使用函数式setState更新状态 clickHandler: function(){ this.setState(function(prevState) { return { clickNo: prevState.clickNo + 1 }; }); } }); var ButtonComponent = React.createClass({ render: function(){ return ( <button onClick={this.props.handleClick}>{this.props.buttonText}{this.props.clickNumber}</button> ) } }); var CommentComponent = React.createClass({ render: function(){ return ( <p>{this.props.commentText}</p> ) } }) ReactDOM.render(<Home />, document.getElementById('root'));
内容的提问来源于stack exchange,提问作者Deadpool
相关产品推荐
相关产品推荐

