简体   繁体   中英

Access this from another class React Native

I am currently factoring my code so as not to repeat the same lines x times, so I created a Functions.js file which I use to call functions from other classes. The problem is, that I cannot execute the function while keeping the properties of this to carry out setState, redirects etc. Here is an example, it will be more telling:

Class in functions.js :

export class KoHttpRequest extends React.Component {
  constructor(props) {
    super(props);

    this.postRequest = this.postRequest.bind(this);
  }

  postRequest = async(url, json, accessToken) => {
    this.setState({loaded: false, validatingAction: false});
    fetch(url, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Authorization' : 'Bearer '.concat(accessToken)
                },
                body: json
            }).then((response) => {
              if (response.ok === true) {
                this.fetchData().then(() => {
                  this.setState({loaded: true}, () => {
                    this.userIsValidatingAnAction();
                    setTimeout(() => {this.setState({validatingAction: false})}, 1000);
                  });
                })
              } else {
                let error = JSON.stringify(response.headers.map);
                this.props.navigation.navigate('Accueil', {failedAction: true, errorReason: error.split('"error-reason":').pop().split('}},')[0].concat(' URL : '.concat(response.url))});
              }
            })
       .catch((error) =>{
        console.error(error);
       });
  }

  render() {
    return null;
  }
}

And in the file where I want to call it :

import { KoHttpRequest } from '../Components&Functions/Koust.js';


createNewInvoice = () => {
     new KoHttpRequest().postRequest('https://koupp.com/apex/rest/mobile/facture', JSON.stringify({
           type:'C',
           numero:this.state.invoiceNumber,
           date_liv:this.state.pickedDate,
           provider_id:this.state.selectedProvider
         }), this.state.accessToken);
   };

So, to explain clearly, in the class, the .then() and .error() are same for all request I do in my app, that's why I need the code here and not in the class that is calling it. Unfortunely, I don't understand how I can tell the function that the 'this' referenced to use is in the other component. Cause actually the function is using themselve props..

Thanks for help.

I'm just trying to access the setState of class that is calling it. In Functions.js, when it's using setState, I want it set the state of the other class actually

EDIT :

I think I found a solution using a callback.

createNewInvoice = () => {
     this.setState({loaded: false, validatingAction: false}, () => {
       new KoHttpRequest().koPostRequest('https://koupp.com/apex/rest/mobile/facture', JSON.stringify({
             type:'C',
             numero:this.state.invoiceNumber,
             date_liv:this.state.pickedDate,
             provider_id:this.state.selectedProvider
           }), this.state.accessToken, this.props, function(result) {
             if (result.status === 200) {
               this.fetchData().then(() => {
                 this.setState({loaded: true}, () => {
                   this.userIsValidatingAnAction();
                   setTimeout(() => {this.setState({validatingAction: false})}, 1000);
                 });
               })
             }
           });
     });
   };

But now, that's the callback function that can't access "this".

EDIT_2:

Find it. Just need to replace function() {..} by () => {..}

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM