javascript - 当我将父类传递给子类时重新渲染值

标签 javascript reactjs react-native

我正在开发一个示例应用程序。实际上,当我将值父类传递给子类时,会多次进入 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/

相关文章:

react-native - NativeModule : AsyncStorage is null, 与 @RNC/AsyncStorage

javascript - ES6 使用不带路径的模块名称导入

reactjs - Material UI Chip数组如何像Angular Chip Input一样使用?

javascript - 如何在 react 表中合并单元格

javascript - React Native 循环这个

node.js - header 崩溃应用程序并出现错误 TypeError : undefined not an object (evaluating 'theme.label' )

javascript - 在 Javascript/jQuery 中对变量数组使用多个 .replace 调用

javascript - 如何向 ng.Iscope 添加属性?

javascript - Owl Carousel "navText:"不添加箭头

javascript - React/javascript 如何将 json 形式的表数据导出到可下载的 Excel 中