阵营本地的,差的构造和componentWillReceiveProps之间
问题描述:
我发展在一类反应过来人,而这出现:阵营本地的,差的构造和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方法,另一方面我不必做任何事情来让组件在传递给它的新道具时更新。
答
构造函数只被调用一次。 componentWillReceiveProps在道具更新时被调用;这是这种逻辑的正确位置。
在您编写任何代码之前,先阅读文档。 https://facebook.github.io/react/docs/component-specs.html – xiaofan2406
https://facebook.github.io/react/docs/component-api.html#setstate – xiaofan2406