简体   繁体   English

从另一个类 React Native 访问它

[英]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.我目前正在分解我的代码,以免重复相同的行 x 次,因此我创建了一个 Functions.js 文件,用于从其他类调用函数。 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:问题是,我无法在保留 this 的属性以执行 setState、重定向等的同时执行该函数。这是一个示例,它会更能说明问题:

Class in functions.js :在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.所以,为了清楚地解释,在类中,我在应用程序中执行的所有请求的 .then() 和 .error() 都是相同的,这就是为什么我需要这里的代码而不是调用它的类。 Unfortunely, I don't understand how I can tell the function that the 'this' referenced to use is in the other component.不幸的是,我不明白我如何告诉函数引用使用的“this”在另一个组件中。 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.我只是想访问调用它的类的 setState。 In Functions.js, when it's using setState, I want it set the state of the other class actually在Functions.js中,当它使用setState时,我希望它实际上设置另一个类的状态

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".但是现在,这是无法访问“this”的回调函数。

EDIT_2:编辑_2:

Find it.找到它。 Just need to replace function() {..} by () => {..}只需要将 function() {..} 替换为 () => {..}

Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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