1.1 无状态组件
无状态组件可以通过减少继承Component而来的生命周期函数而达到性能优化的效果。从本质上来说,无状态组件就是一个单纯的render函数,所以无状态组件的缺点也是显而易见的。因为它没有shouldComponentUpdate生命周期函数,所以每次state更新,它都会重新绘制render函数。
原则上,只要一个组件只具有render函数时,都可以封装成无状态组件,但是我认为其较佳的使用场景应该是使用在ListView组件的renderRow函数内部,因为每次对ListView组件的数据进行操作,都会不可避免的调用renderRow函数,而这时无状态组件无生命周期的特性恰好能有效的显示出来。虽然此时是否将renderRow里面的组件拆分出来在效果上都是一样的,但是组件的拆分有利于降低耦合,也有利于隔离这些单元进行独立测试。
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
ListView,
TouchableOpacity,
} from 'react-native';
const defaultSource = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
const testData = [{uername:'谢广坤',useid:'w1258536653',remark:'这是一条备注信息'},
{uername:'王小绿',useid:'1258012580',remark:''},
{uername:'肖宏',useid:'3215532155',remark:'宵小消失'},
{uername:'李逸',useid:'1008610086',remark:'木子李'}];
export default class Test extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: defaultSource,
};
this.listData = [];
}
componentDidMount() {
this.listData = JSON.parse(JSON.stringify(testData));
this.setState({
dataSource: defaultSource.cloneWithRows(testData),
});
}
updateItem = (index) => {
if (this.listData[index].username == '李明') {
return;
}
this.listData[index].username = '李明';
this.setState({
dataSource: defaultSource.cloneWithRows(this.listData),
});
}
renderRow = (rowData,i,j) => {
console.log('renderRow',rowData.uername);
return (
<SubItem rowData={rowData} updateItem={this.updateItem} index={j}/>
)
}
render() {
return (
<View style={{flex:1,backgroundColor:"#faf7f7"}}>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}/>
</View>
)
}
}
const SubItem = ({rowData,index,updateItem,}) => {
console.log('SubItem.render',rowData.uername);
return (
<View style={styles.itemStyle}>
<TouchableOpacity onPress={()=>updateItem(index)} style={styles.updataBtn}>
<Text style={styles.baseText}>{rowData.uername||''}</Text>
<Text style={{fontSize:12,color:'#fff',paddingLeft:20}}>{'点我修改'}</Text>
</TouchableOpacity>
<Text style={styles.baseText}>{rowData.useid||''}</Text>
<Text style={styles.baseText}>{rowData.remark||'暂无备注'}</Text>
</View>
);
}
const styles = StyleSheet.create({
itemStyle: {
paddingHorizontal: 10,
paddingVertical: 15,
backgroundColor: '#fff',
marginBottom: 5,
},
baseText: {
fontSize: 14,
color: '#000',
},
updataBtn: {
flexDirection: 'row',
alignItems: 'center',
padding: 5,
backgroundColor: '#58A0FF',
}
});
1.2 PureComponent
纯组件是通过控制shouldComponentUpdate生命周期函数,减少render调用次数来减少性能损耗的。这相对于Component来说,减少了手动判断state变化的繁琐操作,但该组件也具有一定的缺陷,因为它只能进行一层浅比较,简单来说,它只比较props和state的内存地址,如果内存地址相同,则shouldComponentUpdate生命周期就返回false。PureComponent的使用场景应该是局部数据发生改变的场景,比如带有输入框、switch开关等的UI组件就可以使用PureComponent组件封装。PureComponent中如果有数据操作最好配合一个第三方组件——Immutable一起使用,Immutable需要使用npm安装该插件才可以使用,因为Immutable可以保证数据的不变性。
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
TextInput,
TouchableOpacity,
} from 'react-native';
export default class Test extends Component {
constructor(props) {
super(props);
this.state = {
accountNum: '',
initPassword: '',
userName: '',
};
}
componentDidMount() {
}
onChangeText = (text, label) => {
this.setState({[label]:text});
}
render() {
return (
<View style={{flex:1,backgroundColor:"#faf7f7"}}>
<InputItem label={'账号:'} holder={'请输入账号'} itemValue={this.state.accountNum} handleChangeText={this.onChangeText} keyboardType={'default'}/>
<InputItem label={'初始密码:'} holder={'请输入初始密码'} itemValue={this.state.initPassword} handleChangeText={this.onChangeText} keyboardType={'numeric'}/>
<InputItem label={'姓名:'} holder={'请输入姓名'} itemValue={this.state.userName} handleChangeText={this.onChangeText} keyboardType={'default'}/>
</View>
)
}
}
class InputItem extends React.PureComponent {
render() {
let {label,holder,itemValue,handleChangeText,keyboardType} = this.props;
console.log('renderInputItem',itemValue);
return (
<View style={styles.inputItemContainer}>
<Text style={{fontSize:14,color:'#000'}}>{label}</Text>
<TextInput
style={styles.customerInput}
underlineColorAndroid={"transparent"}
placeholderTextColor={"#cdcdcd"}
placeholder={holder}
defaultValue={itemValue}
keyboardType={keyboardType}
onChangeText={(text)=>handleChangeText(text,itemValue)}
numberOfLines={1}/>
</View>
)
}
}
const styles = StyleSheet.create({
inputItemContainer: {
backgroundColor: '#fff',
paddingHorizontal: 10,
paddingVertical: 14,
marginBottom: 5,
flexDirection: 'row',
alignItems: 'center'
},
customerInput: {
flex: 1,
minHeight: 25,
paddingHorizontal: 10,
paddingVertical: 0,
textAlign: 'right',
fontSize: 14,
color: '#333',
},
});
个人理解:所谓无状态组件就是没有生命周期的组件(箭头函数return形式);纯组件就是有生命周期的但是只是接受props来作为纯展示组件不做逻辑判断处理的组件(一般常见list组件)