[英]React.js - componentWillReceiveProps only updates every other this.props update
我正在用React v0.14.6构建一个应用程序。 所需的功能是单击GoalItem以显示ModalItem。 目标项目具有一个带有onClick属性的'a'标签,该标签设置了{this.state.showModal:true}。 ModalItem通过showModal属性传递给GoalItem的this.state.showModal。
为了更改ModalItem组件的状态,例如this.state.showModal:this.props.showModal,我在componentWillReceiveProps中使用setState()。
奇怪的是,GoalItem中的'a'标签需要被单击两次才能使模式出现。目标是只需单击一下就足够了。
预先感谢您的帮助。 以下是相关代码。
//goal-item.jsx
var React = require('react');
var ModalItem = require('./modal-item');
module.exports = React.createClass({
getInitialState() {
return {
name: this.props.goal.name,
nameChanged: false,
showModal: false
}
},
open() {
this.setState({ showModal: true });
},
render() {
return <a className="list-group-item"
key={this.props.goal.id}
onClick={this.open}>
<ModalItem goal={this.props.goal} showModal={this.state.showModal} />
</a>
}
});
//modal-item.jsx
var React = require('react');
var Modal = require('react-bootstrap/lib/modal');
var Button = require('react-bootstrap/lib/button');
module.exports = React.createClass({
getInitialState() {
return {showModal: false };
},
componentWillReceiveProps() {
this.setState({ showModal: this.props.showModal });
},
close() {
this.setState({ showModal: false });
},
render() {
return (
<div>
<Modal show={this.state.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>{this.props.goal.name}</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>{this.props.goal.description}</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>Close</Button>
</Modal.Footer>
</Modal>
</div>
);
}
});
在componentWillReceiveProps
您将获得新的道具作为参数。 因此应该是:
componentWillReceiveProps(newProps) {
this.setState({ showModal: newProps.showModal });
}
基本上,这是一个地方,您可以通过使用this.props
访问它们来比较自变量中的新道具与旧道具,然后执行所需的状态更新。
请参阅文档: componentWillReceiveProps
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.