2016-07-28 26 views
1

我發展在一類反應過來人,而這出現:陣營本地的,差的構造和componentWillReceiveProps之間

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方法,另一方面我不必做任何事情來讓組件在傳遞給它的新道具時更新。

+1

在您編寫任何代碼之前,先閱讀文檔。 https://facebook.github.io/react/docs/component-specs.html – xiaofan2406

+0

https://facebook.github.io/react/docs/component-api.html#setstate – xiaofan2406

回答

6

構造函數只被調用一次。 componentWillReceiveProps在道具更新時被調用;這是這種邏輯的正確位置。