我正在开发一个示例应用程序。实际上,当我将值父类传递给子类时,会多次进入 componentWillReceiveProps() 方法重新渲染该值。
这是我的代码:
这是我的家长类(class):
class ParentClass extends React.Component {
constructor (props) {
this.state = {
BadgeValue: 0,
setTabVal: false
}
}
getBadgeLength (badgeValue) {
this.setState({
badgeLength: badgeValue,
setTabVal: true
})
}
render () {
return (
<ChildClass navigator= {this.props.navigator} getBadgeLength={this.getBadgeLength.bind(this)} />
)
}
}
现在我假设了子类:在这种情况下,我实际上再次调用了更新目的,在 componentWillReceiveProps() 中调用相同的方法 但是,我的主要问题是在这种情况下重新渲染次数更多。
class ChildClass extends React.Component {
componentWillReceiveProps () {
var getBadgeValue = array.length
this.props.getBadgeLength(getBadgeValue)
}
componentWillMount () {
var getBadgeValue = array.length
this.props.getBadgeLength(getBadgeValue)
this.setState({
dataSource: this.state.dataSource.cloneWithRows(array)
}, () => {
this.getshopaddressData()
this.getShopDetails()
}
render(){
return()
}
}
最佳答案
首先,您的方法名称应该是 setBadgeLength
因为它会更新值。其次,您应该将徽章值作为 Prop 传递给子类,然后在 child
类中进行比较:
shouldComponentUpdate(nextProps) {
if (this.props.badgeValue != nextProps.badgeValue) {
return false; // don't update if badgeValue is changing
} else {
return true;
}
}
关于javascript - 当我将父类传递给子类时重新渲染值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47180323/