【发布时间】:2019-05-01 19:51:53
【问题描述】:
我遇到了这种奇怪的行为,我的 onClick 方法 handleClick 必须运行两次才能使 CardView 组件能够访问新状态。我想这可能意味着在更新状态时,组件仍在引用 groupedCardInfo 属性的旧状态值?
这是流程,希望能深入了解我哪里出错了:
GroupedRowContainer:
<p onClick={() => { this.props.handleClick(this.props.properties) }}>{this.props.parentName}</p>
然后这会在App.js 中调用以下方法:
handleClick(properties){
console.log("toggle click!")
// this.setState({active : !this.state.active});
this.setState({
active: !this.state.active,
groupedCardInfo: properties
})
}
应该更新App.js 中的以下状态属性:
constructor(props) {
super(props);
this.state = {
genInfoList: [],
groupedObjectsList: [],
// This obj stores data for cases where there's only one property
cardInfo: {
name: data[0].name,
type: data[0].dataType,
usage: data[0].app_keys
},
data: [],
active: false,
// This obj stores data in cases where there are multiple properties to render in the pane
groupedCardInfo: [{
name: "placeholder name"
}]
};
this.changeInfoList = this.changeInfoList.bind(this)
this.handleClick = this.handleClick.bind(this)
}
占位符被替换为properties 对象。这个 prop 被传递给需要它的 CardView 组件,就像在 App.js 中一样:
<CardView name = {this.state.cardInfo.name} type = {this.state.cardInfo.type} usage = {this.state.cardInfo.usage} groupedCardInfo = {this.state.groupedCardInfo}/>
为什么CardView在handleClick方法运行两次时才渲染更新的groupedCardInfo?
【问题讨论】:
标签: reactjs