Компонент не обновляет значение после вызова webService в React Native

Я назвал GET webService в React Native, его успешно получили ответ. Но я хочу установить этот ответ в компоненте. значит, согласно ответу компонент не обновляется. Смотри мой код.

ПОЛУЧИТЬ ЗАПРОС:

 makeRemoteRequest = () => {
   this.setState({ loading: true });
   fetch('http://jsonstub.com/ws/pendingInvoices', {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'JsonStub-User-Key': 'daf0e17a-5951-49e0-8d32-4cb4bb804577',
        'JsonStub-Project-Key': '4e70b1a8-12d0-4fa5-8c34-a99b666bd073',
      }
    })
     .then(res => res.json())
     .then(res => {

       console.log('Data Is : ' ,res);
       this.setState({
         text : res,
         customData : res,
         error: res.error || null,
         loading: false,
         refreshing: false
       });
     })
     .catch(error => {
       console.log('error Is : ' ,error);
       this.setState({ error, loading: false });
     });
 };

Служба называется:

 componentDidMount() {
   this.makeRemoteRequest();
 }

Хотите обновить текст и Аккордеон,

render(){
       const { navigate } = this.props.navigation;
        return (
          <View style = {styles.scrollSty}>
               <Accordion
                  sections={this.state.customData}
                  renderHeader={this._renderHeader.bind(this)}
                  renderContent={this._renderContent.bind(this)}
                />
              <View><Text style = {{color : 'white'}}>{this.state.text}</Text></View>

         </View>
        );
     }
    }

2 ответа

Решение

Ya. Наконец, найдите решение: здесь мы можем обновить компонент двумя способами.

  1. Принудительное обновление: вызов функции после установки значений.

      this.setState({
         customData: customData,
         ...
       });
       this.forceUpdate()
    
  2. Вызов shouldComponentUpdate: если вы не звоните, то не обновляется.

      shouldComponentUpdate(nextProps, nextState) {
        return true;
      }
    

Я полагаю, вам нужно связать makeRemoteRequest метод в конструкторе компонента.

class YourComponent extends Component {
  constructor() {
    this.makeRemoteRequest = this.makeRemoteRequest.bind(this)
  }

  componentDidMount() {
    this.makeRemoteRequest()
  }

  render() {
    ...
  }
}
Другие вопросы по тегам