Как проверить, установлен ли компонент в React-Native ES6
Я устанавливаю прослушиватель в своем приложении и использую обновление силы всякий раз, когда он транслируется, но он дает ошибку forceUpdate не может быть вызван на unmounted компонент. Как я могу проверить, установлен ли компонент сейчас, когда функция isMounted()
устарела.
'use strict';
var React = require('react-native');
import ExpAndroid from './ExpAndroid';
var {
AppRegistry,
Image,
ListView,
TouchableHighlight,
StyleSheet,
Text,
View,
Component,
AsyncStorage,
Navigator,
DeviceEventEmitter
} = React;
var rowID;
var img=require('./resource/ic_pause_white.png');
class Example1 extends Component{
constructor(props) {
super(props);
this.state = {
};
}
componentWillMount(){
rowID = this.props.rowIdentity;
console.log("rowID "+rowID);
}
componentDidMount(){
console.log('component mounted')
this.start();
DeviceEventEmitter.addListener('playMusicStatus', (data)=> {
if(data.playMusic==true){
img=require('./resource/ic_pause_white.png');
rowID++;
this.setState(this.state);
ExpAndroid.someMethod1("someurl);
}
});
}
componentWillUnmount(){
console.log('componentwill unmounted')
}
start() {
var url = "some url";
ToastAndroid.prepareToPlay(url,true);
}
render() {
return (
<Image source={require('./resource/album_back.png')} style={styles.background}>
<Image
source={{uri:this.state.trackDetails[rowID].thumnail_loc}}
style={styles.thumbnail}
/>
<View style={styles.flowRow}>
<Text
style={styles.titles}
>text1 + {rowID}: </Text>
<Text
style={styles.titles}
>{this.state.details[rowID].text1}</Text>
</View>
<View style={styles.flowRow}>
<Text
style={styles.titles}
>text2 : </Text>
<Text
style={styles.titles}
>{this.state.details[rowID].text2}</Text>
</View>
<View style={styles.flowRow}>
<Text
style={styles.titles}
>Text3 : </Text>
<Text
style={styles.titles}
>{this.state.Details[rowID].Text3}</Text>
</View>
<View style={styles.flowRow}>
<Text
style={styles.titles}
>Text4 : </Text>
<Text
style={styles.titles}
>{this.state.details[rowID].Text4}</Text>
</View>
</Image>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
},
background: {
flex: 1,
width: null,
height: null,
},
flowRow : {
flexDirection :'row',
},
flowRowPlay : {
flexDirection :'row',
alignSelf:'center',
},
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch'
},
thumbnail: {
width: 100,
height: 120,
alignSelf:'center',
margin :30
},
controls: {
width: 30,
height: 30,
margin:20
},
titles: {
fontSize: 15,
margin:20,
color: 'white',
},
timings: {
fontSize: 12,
margin:5,
color: 'white',
},
});
module.exports = Example1;
Ответы
Ответ 1
Вы можете справиться с этим сами в своем компоненте:
componentDidMount() {
this._mounted = true;
}
componentWillUnmount() {
this._mounted = false;
}
Затем вы можете проверить значение this._mounted
в своем слушателе.
Обратите внимание, что следует избегать использования forceUpdate()
https://facebook.github.io/react/docs/component-api.html#forceupdate
Обычно вы должны стараться избегать всех применений forceUpdate() и только читать из this.props и this.state в render(). Это делает ваш компонент "чистым" и ваше приложение намного проще и эффективнее.
Ответ 2
Используя ReactUpdateQueue
, вы можете избежать управления собственным состоянием isMounted
.
const ReactUpdateQueue = require('ReactUpdateQueue');
// Pass the ref to your component.
if (ReactUpdateQueue.isMounted(view)) {
// Your component is mounted!
}
Ответ 3
То, что я сделал, это изменить обратный вызов в componentWillMount.
let asyncCallback;
componentDidMount(){
asyncCallback = res=> this.setState({data: res});
asyncTask(asyncCallback);
}
componentWillUnmount(){
asyncCallback = ()=> console.log("AsyncCallback called but component has unmounted");
}