【问题标题】:React-native, difference between constructor and componentWillReceivePropsReact-native,构造函数和componentWillReceiveProps的区别
【发布时间】:2016-12-03 12:23:30
【问题描述】:

我正在用 react native 开发几个类,结果如下:

class Foo extends Component {
  constructor(props) {
    super(props)
    this.state = {
      days: [{text: 'Sofort', id: 1, selected: true}, {text: 'Morgen', id: 2, selected: false}, {text: 'Montag', id: 3, selected: false}, {text: 'Samstag', id: 4, selected: false}, {text: 'Sonntag', id: 5, selected: false}]
    }
  }

  onDaySelection(selectedDay) {
    // some logic to change the selected day
  }

  render() {
    <Bar data={this.state.days} callback={this.onDaySelection(selectedDay)}>
  }
}

酒吧类:

class Bar extends Component {
  constructor(props) {
    super(props)

    let dataSource = new ListView.DataSource(
      {rowHasChanged: (r1, r2) => r1.id !== r2.id}
    )

    this.state = {
      dataSource: dataSource.cloneWithRows(this.props.days),
    }
  }

  componentWillReceiveProps(newProps) {
    let dataSource = new ListView.DataSource(
      {rowHasChanged: (r1, r2) => r1.id !== r2.id}
    )

    this.state = {
      dataSource: dataSource.cloneWithRows(newProps.days),
    }
  }

  renderRow(rowData) {
    let tick = rowData.selected? (
      <Image source={require('../assets/images/Checkbox.png')}/>
    ): (
      <Image source={require('../assets/images/CheckboxEmpty.png')}/>
    )
    return (
      <View>
        <TouchableOpacity
          onPress={ () => {this.props.callback(rowData)}}
          style={appStyles.flowRight}
        >
          {tick}
          <Text>{rowData.text}</Text>
        </TouchableOpacity>
      </View>
    )
  }

  render() {
    return (
      <ListView
      dataSource={this.state.dataSource}
      renderRow={this.renderRow.bind(this)}
      />
    )
  }
}

如您所见,我必须在 Bar 类上实现方法 componentWillReceiveProps,这是为什么呢?为什么没有再次调用构造函数,是因为商店没有被更新吗?这是一个正确的模式吗?

编辑:似乎我的问题并不清楚,因为还有其他组件接收道具,只有一个构造函数并在它们的道具更新时相应地更新,例如:

class CustomCarouselIndicator extends Component {

  constructor(props) {
    super(props)
  }

  render() {
    let indicatorArray = []
    for(let i = 0; i < this.props.length; i++) {
      indicatorArray.push(i)
    }

    let indicators = indicatorArray.map(index => {
      let isSelected = index == this.props.selected
      //Some more logic
    })

    return (
      <View style={[appStyles.flowRight, {flex: 1, justifyContent: 'center', alignItems:'center'}, this.props.style]}>
        {indicators}
      </View>
    )
  }
}

每当我更改选定的道具时,组件都会更新,无需实现 componentWillReceiveProps。

这两个类都在我的代码库中使用,但一方面我必须实现 will receive props 方法,另一方面我不需要做任何事情来让组件在新的 props 传递给它时更新。

【问题讨论】:

标签: reactjs react-native redux


【解决方案1】:

构造函数只被调用一次。每当更新 props 时都会调用 componentWillReceiveProps;这是这种逻辑的正确位置。

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 2015-08-20
    • 1970-01-01
    • 2016-06-16
    • 2019-01-01
    • 2018-08-09
    • 2011-06-01
    相关资源
    最近更新 更多