【发布时间】:2019-03-21 18:13:28
【问题描述】:
我在 react 中做了一个条件渲染语句。我正在检查的条件是基于服务器响应的。如果满足条件,那么我必须呈现一些 UI 组件,否则会呈现不同的 UI。所以问题是我从服务器得到了什么,只有其他部分在工作。我也仔细检查了response。
更新代码
export default class ViewStatus extends Component {
constructor(props) {
super(props);
this.initialState = {
progressData: [],
};
this.state = this.initialState;
}
componentWillMount(){
fetch('http://192.168.1.2:3000/api/progress',{
method:'POST',
headers:{
'Accept': 'application/json',
'Content-Type':'application/json'
},
body:JSON.stringify({
work_type:this.props.work_type
})
})
.then(response => response.json())
.then((responseData) => {
this.setState({
progressData:responseData[0]
});
});
}
render() {
const isResponseData = this.state.progressData == '1' ? this.renderDone() : this.renderInProgress()
console.log(this.state.progressData);
return(
<View>
{isResponseData}
</View>
);
}
renderInProgress(){
return(
<View>
<Text>In Progress</Text>
<Text>Worker will approach you within 24 hrs.</Text>
</View>
);
}
renderDone(){
return(
<View>
<Text>Successfull</Text>
<Text>Are you satisfied with the work .If yes please mark done.</Text>
</View>
);
}
【问题讨论】:
-
你能检查一下你从服务器得到了什么吗?有一个断点或 console.log 那里
-
收到响应后是否更新状态?
-
首先检查控制台中 this.state.progressData 值的类型,如果是整数则使用 === 1 或者如果其字符串使用 === '1'。或者如果值为 0 或 1,则无需使用比较运算符,您可以直接应用。 (this.state.progressData)? '真案例' : '假案例';
-
是的,我在渲染中安慰了
progressData。我最初得到一个空数组,但后来我得到了响应。为什么这样请检查这个i.stack.imgur.com/p7Xgi.png。还更新了我上面的代码 -
progressData 有一个成员“status”,你不应该检查progressData.status 吗?
标签: javascript reactjs react-native conditional-rendering