【发布时间】:2016-02-26 09:10:57
【问题描述】:
我有这两个简化 React 组件,其中Times 组件是Create 组件的子组件(请参阅下面的代码示例)。预期的行为是,最初,Times 组件未显示,但当用户单击带有onClick 的链接时,Times 组件出现。
组件大部分都按预期工作,但奇怪的是,在第一次单击onClick 链接后,Times 组件没有出现,Create 组件根本没有改变状态,因为显示在控制台中。但是,当第二次单击该链接时,Create 组件确实会更改状态并重新渲染,并且会看到 Times 组件。
创建.jsx
import React from 'react';
import Times from './Times.jsx';
export default React.createClass({
getInitialState: function () {
return {times: false};
},
_change: function () {
this.replaceState({times: true});
console.log(this.state.times);
},
render: function () {
return (
<div id="create">
<div id="outerbox">
<a onClick={this._change}>Times</a>
<Times shouldShow={this.state.times}/>
</div>
</div>
);
}
});
Times.jsx
import React from 'react';
export default React.createClass({
propTypes: {
shouldShow: React.PropTypes.bool.isRequired
},
getDefaultProps: function () {
return {shouldShow: false};
},
getInitialState: function () {
return {el: 'times'};
},
componentDidMount: function() {
if (this.props.shouldShow === false) {
this.setState({display: 'none'});
} else {
this.setState({display: 'block'});
}
},
componentWillReceiveProps: function() {
if (this.props.shouldShow === false) {
this.setState({display: 'none'});
} else {
this.setState({display: 'block'});
}
},
render: function () {
return (
<div id={this.state.el} style={{"display": this.state.display}}>
<h1>Times</h1>
</div>
);
}
});
console.log 的输出
false
true
为什么Create组件的状态在第一次点击时没有注册?
【问题讨论】:
标签: javascript reactjs components state