我对新的平面列表组件有意见.具体地说,它不会重新命名它的行,即使props 显示该行取决于更改.
FlatList docs说:
这是一个PureComponent,这意味着如果
THE QUESTION
然而,当我更改selectedCategory项的ID时——该props 应该指示行是否为"已 Select 的"——我认为props 应该重新命名.我弄错了吗?
我判断了列表和行组件的"componentWillReceiveProps"方法,列表可以很好地接收更新,但从未调用行的生命周期方法.
如果我在列表组件中包含一个随机的、无用的布尔状态值,并在props 更新时来回切换它,它就会工作——但我不知道为什么?
state = { updated: false };
componentWillReceiveProps(nextProps) {
this.setState(oldstate => ({
updated: !oldstate.updated,
}));
}
<FlatList
data={this.props.items.allAnimalCategories.edges}
renderItem={this._renderRow}
horizontal={true}
keyExtractor={(item, index) => item.node.id}
randomUpdateProp={this.state.updated}
/>
THE CODE
我的代码的 struct 是这样的:我有一个包含所有逻辑和状态的容器组件,其中包含一个平面列表组件(presentational,no state),它同样包含一个定制的presentational行.
Container
Custom list component that includes the FlatList component
(presentational, stateless) and the renderRow method
Custom row (presentational, stateless)
容器包括以下组件:
<CustomList
items={this.props.viewer}
onCategoryChosen={this._onCategoryChosen}
selectedCategory={this.state.report.selectedCategory}
/>
客户列表:
class CustomList extends Component {
_renderRow = ({ item }) => {
return (
<CustomListRow
item={item.node}
selectedCategory={this.props.selectedCategory}
onPressItem={this.props.onCategoryChosen}
/>
);
};
render() {
return (
<View style={_styles.container}>
<FlatList
data={this.props.items.categories.edges}
renderItem={this._renderRow}
horizontal={true}
keyExtractor={(item, index) => item.node.id}
randomUpdateProp={this.state.updated}
/>
</View>
);
}
}
(数据来自继电器)
最后一行:
render() {
const idsMatch = this.props.selectedCategory.id == this.props.item.id;
return (
<TouchableHighlight onPress={this._onItemPressed}>
<View style={_styles.root}>
<View style={[
_styles.container,
{ backgroundColor: this._getBackgroundColor() },
]}>
{idsMatch &&
<Image
style={_styles.icon}
source={require('./../../res/img/asd.png')}
/>}
{!idsMatch &&
<Image
style={_styles.icon}
source={require('./../../res/img/dsa.png')}
/>}
<Text style={_styles.text}>
{capitalizeFirstLetter(this.props.item.name)}
</Text>
</View>
<View style={_styles.bottomView}>
<View style={_styles.greyLine} />
</View>
</View>
</TouchableHighlight>
);
}
这一行没有那么有趣,但我加入它是为了表明它完全是无状态的,并且依赖于它的父母props .
状态更新如下:
_onCategoryChosen = category => {
var oldReportCopy = this.state.report;
oldReportCopy.selectedCategory = category;
this.setState(Object.assign({}, this.state, { report: oldReportCopy }));
};
该州的情况如下:
state = {
...
report: defaultStateReport,
};
const defaultStateReport = {
selectedCategory: {
id: 'some-long-od',
name: '',
},
...
};