На условный рендеринг реагируют нативные: только часть работает - PullRequest
0 голосов
/ 17 октября 2018

Я сделал оператор условного рендеринга в реакции. Проверяемое условие основано на ответе сервера.Если условие выполнено, то я должен отобразить некоторые компоненты пользовательского интерфейса, в противном случае другой пользовательский интерфейс.Так что проблема в том, что я получаю с сервера, работает только другая часть. Я также дважды проверил 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 голосов
/ 17 октября 2018
  1. Вам необходимо вызвать responseData [0] .status, чтобы получить значение из API.
  2. Вызовы API должны происходить только в componentDidMount
  3. componentWillMount устарела, поэтому забудьтеоб этом методе
  4. Просто используйте троичный оператор для отображения содержимого вместо нескольких функций.

Попробуйте использовать приведенный ниже код.

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

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...