以下是我的代码
class Court extends React.Component {
constructor(props) {
super(props);
this.state = {
clubs: [],
clubId: 0
};
this.onClubChange = this.onClubChange.bind(this);
};
componentDidMount() {
if(this.props.auth.user.type == 'admin'){
this.props.fetchClubs().then(
(res) => this.setState({
clubs: this.props.clubs
})
);
}
else {
this.props.fetchClubs(this.props.auth.user.id).then(
(res) => this.setState({
clubs: this.props.clubs
})
);
}
}
onClubChange(e){
this.setState({ clubId: e.target.value});
}
render() {
const { clubs, clubId } = this.state;
var clubsOptions = clubs.map(function(club){
return (
<option key={club.id} value={club.id}>{club.clubName}</option>
);
});
return (
<div>
<form>
<div className={classnames('form-group')}>
<label className="control-label">Clubs</label>
<select
name = "clubId"
onChange={this.onClubChange}
className='form-control'
value={ clubId }>
<option value="0">Select Club...</option>
{ clubsOptions }
</select>
</div>
</form>
{ this.state.clubId != 0 ? <Courts clubId={this.state.clubId} /> : null }
</div>
);
}
}
Court.propTypes = {
auth: React.PropTypes.object.isRequired,
clubs: React.PropTypes.array.isRequired,
fetchClubs: React.PropTypes.func.isRequired
}
function mapStateToProps(state) {
return {
clubs: state.clubs.clubs,
auth: state.auth
}
}
export default connect(mapStateToProps, { fetchClubs })(Court);
当我更改下拉列值时,会发生状态更改,但子组件Courts中的数据未更新
{ this.state.clubId != 0 ? <Courts clubId={this.state.clubId} /> : null }
其次,从下拉列表中首次选择选项会显示完美数据,但之后不会显示任何更改
我做错了什么?
答案 0 :(得分:0)
以这种方式试试;
class Court extends React.Component {
constructor(props) {
super(props);
this.state = {
clubs: [],
clubId: 0
};
this.onClubChange = this.onClubChange.bind(this);
};
componentDidMount() {
if(this.props.auth.user.type == 'admin'){
this.props.fetchClubs().then(
(res) => this.setState({
clubs: this.props.clubs
})
);
}
else {
this.props.fetchClubs(this.props.auth.user.id).then(
(res) => this.setState({
clubs: this.props.clubs
})
);
}
}
onClubChange(e){
this.setState({ clubId: e.target.value});
}
render() {
const { clubs, clubId } = this.state;
var clubsOptions = clubs.map(function(club){
return (
<option key={club.id} value={club.id}>{club.clubName}</option>
);
});
let courts = <Courts clubId={this.state.clubId} />;
let courtsView = this.state.clubId != 0 ? courts : null;
return (
<div>
<form>
<div className={classnames('form-group')}>
<label className="control-label">Clubs</label>
<select
name = "clubId"
onChange={this.onClubChange}
className='form-control'
value={ clubId }>
<option value="0">Select Club...</option>
{ clubsOptions }
</select>
</div>
</form>
{ courtsView }
</div>
);
}
}
Court.propTypes = {
auth: React.PropTypes.object.isRequired,
clubs: React.PropTypes.array.isRequired,
fetchClubs: React.PropTypes.func.isRequired
}
function mapStateToProps(state) {
return {
clubs: state.clubs.clubs,
auth: state.auth
}
}
export default connect(mapStateToProps, { fetchClubs })(Court);
&#13;