条件渲染响应本机:只有其他部分在起作用

时间:2018-10-17 06:30:34

标签: javascript reactjs react-native conditional-rendering

我已经在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>
     );
  }

1 个答案:

答案 0 :(得分:1)

  
      
  1. 您需要调用responseData [0] .status以从API获取值。
  2.   
  3. API调用应仅在componentDidMount中发生
  4.   
  5. componentWillMount已被弃用,所以请不要使用此方法
  6.   
  7. 只需使用三元运算符即可呈现内容,而不是使用多个函数。
  8.   

尝试以下代码。

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>
    );
  }

}