![](/img/trans.png)
[英]Is it possible to access a useRef variable from another class component in react native?
[英]Access this from another class React Native
我目前正在分解我的代碼,以免重復相同的行 x 次,因此我創建了一個 Functions.js 文件,用於從其他類調用函數。 問題是,我無法在保留 this 的屬性以執行 setState、重定向等的同時執行該函數。這是一個示例,它會更能說明問題:
在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;
}
}
在我想調用它的文件中:
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);
};
所以,為了清楚地解釋,在類中,我在應用程序中執行的所有請求的 .then() 和 .error() 都是相同的,這就是為什么我需要這里的代碼而不是調用它的類。 不幸的是,我不明白我如何告訴函數引用使用的“this”在另一個組件中。 因為實際上該功能正在使用它們自己的道具..
感謝幫助。
我只是想訪問調用它的類的 setState。 在Functions.js中,當它使用setState時,我希望它實際上設置另一個類的狀態
編輯 :
我想我找到了使用回調的解決方案。
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);
});
})
}
});
});
};
但是現在,這是無法訪問“this”的回調函數。
編輯_2:
找到它。 只需要將 function() {..} 替換為 () => {..}
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.