React-native,构造函数和componentWillReceiveProps之间的区别

时间:2016-07-28 22:24:35

标签: reactjs react-native redux

我正在开发一些反应原生的类,这就出现了:

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。

这两个类都在我的代码库中使用,但在一个我必须实现将接收道具方法,另一方面我没有做任何事情来让组件在传递给它的新道具时更新。

1 个答案:

答案 0 :(得分:6)

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