const baseURL = "https://api.app.net";
function fetchAction(...props) {
this.url = props.shift(1);
this.options = props.shift(1);
return fetch(this.url, Object.assign({}, this.options))
.then((response) => response.json() );
}
export default {
getTest() {
var apiPort = "stream/0/posts/stream/global";
return fetchAction(`${baseURL}/${apiPort}`, {
method: 'get',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
}
};
import BaseServiceApiNet from './BaseServiceApiNet';
import SecondPage from './secondPage';
export default class FirstPage extends Component {
constructor(props){
super(props);
this.state ={
isLoading:false,
resultJson:null
};
}
componentDidMount(){
this._isViewMounted=true;
}
componentWillUnmount(){
this._isViewMounted=false;
}
sendTestRequest(){
if(this.state.isLoading==true){
return;
}
this.setState({
resultJson:null,
isLoading:true
});
try {
BaseServiceApiNet.getTest()
.then((response) => {
if (this._isViewMounted==false||this._isViewMounted==null) {
return;
}
let data = response.meta;
this.setState({
resultJson:data==null?null:JSON.stringify(data),
isLoading:false
});
//console.log("返回数据:"+JSON.stringify(data));
})
} catch(e) {
alert(e);
this.setState({
isLoading:false
});
}
}
goNextPage(){
const {navigator} = this.props;
if(navigator!=null){
navigator.push({
name:'SecondPage',
component:SecondPage
});
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.button} onPress={this.goNextPage.bind(this)}>下一个界面</Text>
<ActivityIndicator color="#fff" size ={'large'} animating={this.state.isLoading} />
<Text style={styles.welcome} onPress={this.sendTestRequest.bind(this)}>
测试网络1
</Text>
<Text style={styles.instructions}>
{this.state.resultJson}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#198668',
},
button: {
fontSize: 20,
textAlign: 'center',
margin: 20,
color:'white',
backgroundColor:'#666',
padding:10
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
padding:10,
backgroundColor:'orange',
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
Call fetch for network requests when a request is not completed ,the resulting memory leaks(iOS and Android)
on iPhone simulator :(instrument check)

on Android Studio tip:

code (BaseServiceApiNet.js):
code (firstPage.js):
How to avoid memory leaks ?
Hope to get your help ,thanks