React native 如何在componentDidMount中使用if/else和responseJson?
我有一个React native 如何在componentDidMount中使用if/else和responseJson?,react-native,React Native,我有一个componentDidMount,我想通过listView显示一些数据。现在我想检查是否存在任何数据,所以我通过if/else检查,但它不起作用,并且总是if为真 我将log.console放在componentDidMount中以显示responseJson,现在显示none 但是当我有一些其他数据,比如产品如果是真的的话 componentDidMount(){ const { navigation } = this.props; const cat = na
componentDidMount
,我想通过listView
显示一些数据。现在我想检查是否存在任何数据,所以我通过if/else
检查,但它不起作用,并且总是if
为真
我将log.console
放在componentDidMount
中以显示responseJson
,现在显示none
但是当我有一些其他数据,比如产品如果是真的
的话
componentDidMount(){
const { navigation } = this.props;
const cat = navigation.getParam('cat');
fetch('products.php',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-type':'application/json'
},
body:JSON.stringify({
cat:cat
})
}).then((response)=>response.json()).
then((responseJson)=>{
console.log(responseJson);
if (responseJson=='none') {
this.setState({
isLoading:false,
empty:true,
});
}else{
let ds = new ListView.DataSource({rowHasChanged:(r1,r2)=>r1!=r2});
this.setState({
isLoading:false,
dataSource:ds.cloneWithRows(responseJson)
});
}
}).done();
}
查看代码后,您似乎想检查responseJson是否为空。如果为空,则将状态设置为空,否则使用响应数据设置状态
首先,不要像你们做的那个样申请检查整个对象
if(responseJson='none'){
相反,您可以检查随数据一起出现的错误
if (responseJson.error === true) {
this.setState({
isLoading:false,
empty:true,
});
}else{
let ds = new ListView.DataSource({rowHasChanged:(r1,r2)=>r1!=r2});
this.setState({
isLoading:false,
dataSource:ds.cloneWithRows(responseJson)
});
}
或者,您可以对数据进行检查
if (responseJson.data === null) {
this.setState({
isLoading:false,
empty:true,
});
}else{
let ds = new ListView.DataSource({rowHasChanged:(r1,r2)=>r1!=r2});
this.setState({
isLoading:false,
dataSource:ds.cloneWithRows(responseJson)
});
}
responseJson.error??我没有错误。我有两个响应。1:Json数据。2:none。none是字符串,由php打印。