[英]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.