【发布时间】:2017-11-23 11:14:01
【问题描述】:
我正在编写一个小型 ReactNative 应用程序,它允许用户邀请人们参加活动。
该设计包括一个受邀者列表,每个受邀者都附有一个复选框,用于邀请/取消邀请所述受邀者。列表顶部的另一个复选框同时对所有被邀请者执行批量邀请/取消邀请。最后,最终将使用一个按钮来发送邀请。
因为每个元素的状态取决于另一个元素所做的更改,所以每当用户对其中一个元素执行操作时,我经常需要重新渲染整个 UI。但是,虽然这可以正常工作,但它给我带来了很多性能问题,as shown in this video
这是我正在使用的代码:
import React, { Component } from 'react';
import { Container, Header, Title,
Content, Footer, FooterTab,
Button, Left, Right,
Center, Body, Text, Spinner, Toast, Root , CheckBox, ListItem, Thumbnail} from 'native-base';
import { FlatList, View } from 'react-native';
export default class EventInviteComponent extends Component {
constructor(props) {
super(props);
console.disableYellowBox = true;
this.state = {
eventName: "Cool Outing!",
invitees:[]
}
for(i = 0; i < 50; i++){
this.state.invitees[i] = {
name: "Peter the " + i + "th",
isSelected: false,
thumbnailUrl: 'https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/62/08/7e/62087ed8-5016-3ed0-ca33-50d33a5d8497/source/512x512bb.jpg'
}
}
this.toggelSelectAll = this.toggelSelectAll.bind(this)
}
toggelSelectAll(){
let invitees = [...this.state.invitees].slice();
let shouldInviteAll = invitees.filter(invitee => !invitee.isSelected).length != 0
let newState = this.state;
newState = invitees.map(function(invitee){
invitee.isSelected = shouldInviteAll;
return invitee;
});
this.setState(newState);
}
render() {
let invitees = [...this.state.invitees];
return (
<Root>
<Container>
<Content>
<Text>{this.state.eventName}</Text>
<View style={{flexDirection: 'row', height: 50, marginLeft:10, marginTop:20}}>
<CheckBox
checked={this.state.invitees.filter(invitee => !invitee.isSelected).length == 0}
onPress={this.toggelSelectAll}/>
<Text style={{marginLeft:30 }}>Select/deselect all</Text>
</View>
<FlatList
keyExtractor={(invitee, index) => invitee.name}
data={invitees}
renderItem={(item)=>
<ListItem avatar style={{paddingTop: 20}}>
<Left>
<Thumbnail source={{ uri: item.item.thumbnailUrl}} />
</Left>
<Body>
<Text>{item.item.name}</Text>
<Text note> </Text>
</Body>
<Right>
<CheckBox
checked={item.item.isSelected}/>
</Right>
</ListItem>}/>
</Content>
<Footer>
<FooterTab>
<Button full
active={invitees.filter(invitee => invitee.isSelected).length > 0}>
<Text>Invite!</Text>
</Button>
</FooterTab>
</Footer>
</Container>
</Root>);
}
}
【问题讨论】:
-
我在这里有一些建议:#1。您不需要在渲染函数中克隆数组。 #2。状态不应该像您那样包含所有内容。我认为这可能是受邀者的 ID 数组。 #3。奇怪的是,FlatList 在这里没有任何改进。您可能希望获取对复选框的引用并切换每个复选框,而不是重新渲染所有内容。希望对您有所帮助
标签: react-native react-native-android react-native-flatlist