gpt4 book ai didi

javascript - 条件渲染 react native :only else part is working

转载 作者:行者123 更新时间:2023-11-30 20:06:41 25 4
gpt4 key购买 nike

我已经在 react 中完成了一个条件渲染语句。我正在检查的条件是基于服务器响应。如果满足条件,那么我必须呈现一些 UI 组件,否则呈现不同的 UI。所以问题是我从服务器得到了什么,只有 else 部分在工作。我也仔细检查了 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>
);
}

最佳答案

  1. You need to call responseData[0].status to get the value from API.
  2. API calls should happen in componentDidMount only
  3. componentWillMount is deprecated so forget about this method
  4. Just use ternary operator to render content instead of multiple functions.

试试下面的代码。

export default class ViewStatus extends Component {
constructor(props) {
super(props);
this.state = {progressData: ""};
}
componentDidMount(){
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].status
});
});
}
render() {
const { progressData }= this.state;
return(
<View>
{progressData == "1" &&
(<View><Text>Successfull</Text>
<Text>Are you satisfied with the work .If yes please mark done.</Text></View>)}
{progressData == "2" &&
(<View><Text>Successfull</Text>
<Text>Are you satisfied with the work .If yes please mark done.</Text></View>)}
{progressData == "" &&(<View><Text>In Progress</Text>
<Text>Worker will approach you within 24 hrs.</Text></View>)}
</View>
);
}

}

关于javascript - 条件渲染 react native :only else part is working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52848549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com