[英]React-select: selected option doesn't stick
我是 React 的新手,需要一些幫助來查看我做錯了什么:-(
我有一個組件,叫做 Bucket,每個 Bucket 可以有多個挑戰,它是單獨的組件,它看起來像這樣,
代碼的簡化版本是這樣的:
class CLL_Bucket extends Component {
constructor(props) {
super(props);
this.state = {};
this.state = {
…
bucketChallengesIdx: 0, // to track the index of challegnes
bucketChallenges: this.props.bucket.bucketChallenges || [],
…
};
…
this.onBucketChallengeIDChanged = this.onBucketChallengeIDChanged.bind(this);
…
}
render() {
const bucketIdx = this.props.idx;
return (
<div style={styles.container}>
<div key={bucketIdx} className="row" style={styles.bucketStyle}>
<div className="col-md-2">
…
</div>
<div key={bucketIdx} className="col-md-4">
<div>
…
</div>
<CLL_BucketChallengeDetail
challenges={this.props.challenges}
bucketChallengesIdx={this.state.bucketChallengesIdx}
bucketChallenges={this.state.bucketChallenges}
onBucketChallengeChanged={(challengeIdx, key, value) => this.onBucketChallengeChanged(challengeIdx, key, value)}
/>
</div>
…
</div>
</div>
);
}
class CLL_BucketChallengeDetail extends Component {
constructor(props) {
super(props);
this.state = {
bucketChallenges: this.props.bucketChallenges,
bucketChallengeID: ""
};
this.onBucketChallengeIDChanged = this.onBucketChallengeIDChanged.bind(this);
…
}
render() {
return (
<div className="col-md-4">
<div>
…
</div>
<table className="table table-bordered table-striped show">
<thead>
<tr>
<th>Challenge ID</th>
<th>Weight</th>
<th>Weight % Ratio</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.props.bucketChallenges.map(this.renderChallengeDetail.bind(this))}
</tbody>
</table>
</div>
);
}
renderChallengeDetail(currentChallenge, index){
const challengeIDOptions = this.props.challenges.map(data => {
return {value: data.ID, label: data.ID}
});
…
return (
<tr key={index}>
<td className="col-xs-3 input-group-sm">
<Select
options={challengeIDOptions}
defaultValue={challengeIDOptions[0]}
onChange={(option)=>this.onBucketChallengeIDChanged(index, option)}
isSearchable={true}
/>
</td>
…
</tr>
);
}
onBucketChallengeIDChanged(challengeIdx, option){
var newChallengeList = this.state.bucketChallenges.map((item, j) => {
if (j === challengeIdx) {
// found the specific challenge in the list that needs to be updated
item.ID = option.value;
}
return item;
});
this.setState({bucketChallenges:newChallengeList, bucketChallengeID:option.value},
() => {console.log("HERE: "+ this.state.bucketChallengeID); this.props.onBucketChallengeChanged(challengeIdx, 'ID', option.value);});
}
}
export default CLL_BucketChallengeDetail;
我遇到的問題是,在更改挑戰 ID 后,它確實顯示在選擇字段中,我可以從 React 開發人員工具中看到該值已更改,即使 setState 正在將正確的值設置為此。 state.bucketChallengeID。 但是,在我切換到應用程序的不同選項卡並返回后,更改后的選擇字段將恢復為上一個。 我究竟做錯了什么??? 提前感謝幫助!
看起來您總是將默認值設置為defaultValue={challengeIDOptions[0]}
。 因此,當您的組件加載時,它將重置為此默認值。 如果每次切換選項卡時都安裝這些組件,則需要使用上下文或其他狀態管理工具來保持狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.