react-native 之"Cannot update during an exitsting sta
react-native 业务逻辑:在页面 而代码是这样的,下面的代码是会出现上面错误的代码 在 export default class xxComponent extends Component {
...
..
onSelectThemeItem(key) {
this.props.onModalClose();
this.themeDao.saveTheme(ThemeFlags[key]);
//发送通知,通知修改主题
DeviceEventEmitter.emit('ACTION_BASE',ACTION_NOTIFY.changeTheme,ThemeFactory.createTheme(ThemeFlags[key]))
}
getThemeItem(key) {
let themeTitle = <TouchableOpacity style={{flex: 1}} onPress={this.onSelectThemeItem(key)}>
<View style={[{backgroundColor: ThemeFlags[key]},styles.themeItem]}>
<Text style={{color: 'white',fontWeight: '300'}}>{key}</Text>
</View>
</TouchableOpacity>;
return themeTitle;
}
...
..
}
而这里出现的问题:view绘制中,再次更改props,导致view会再次去render,报错!就在14行的代码..
解决问题方法: 分析” 首先了解下平时我们写bind()方法和箭头函数的几种形式 ...
xxFunction(){..}
...
<XXView xxxx={this.xxFunction.bind(this)} />
第二种 constructor(props) {
super(props);
this.xxFunction= this.xxFunction.bind(this);
}
...
xxFunction(){..}
...
第三种 ...
xxFunction= ()=>{..};
...
<XXView xxxx={this.xxFunction} />
第四种 ...
xxFunction(){..}
...
<XXView xxxx={()=>this.xxFunction()} />
bind函数和箭头函数区别: 通过 bind() 函数会创建一个新函数(称为绑定函数),该新函数是由指定的this值和初始化参数改造的原函数拷贝。 好的,让我们一同看下代码 /** * Created by YJH on 2018/6/13. */
import React,{Component} from 'react';
import {
BackAndroid,} from 'react-native';
export default class Backforward{
constructor(props){
this.backpress = this.onHardwareBackforward.bind(this);
this.props=props;//由于不是component组件,所以后面使用props时候,需要将props通过this.props存储起来
}
componentDidMount(){
if(this.props.backforward){
BackAndroid.addEventListener("backforward",this.backpress);
}
}
componentWillUnmount(){
if(this.props.backforward){
BackAndroid.removeEventListener("backforward",this.backpress);
}
}
onHardwareBackforward(e){
return this.props.backforward(e);
}
}
通过bind绑定函数 就是下面代码 export default class xxDetailPage extends Component {
constructor(props) {
super(props);
//实现对android手机返回按钮的监听返回功能
this.backforward = new Backforward({backforward: (e) => this.onBackforward(e)}); ... } componentDidMount(){ this.backforward.componentDidMount(); } componentWillUnmount(){ this.backforward.componentWillUnmount(); } onBackforward(e) { this.goBack(); return true; } goBack() { if (this.state.isBack) { this.webView.goBack(); } else { this.props.navigator.pop(); } } ... .. }
即 参考内容: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |