我試圖顯示公司的名稱。因此我調用了一個函數getCompanyByShortlink,我想在這裏爲company.com分配一個值company_name。我檢查了響應,它包含了我需要的所有數據,所以這裏沒有問題。在我的渲染函數中反應本機設置變量
但是,這不起作用,值不分配。如果我輸入return this.company =「test」;直接,它工作得很好。
我真的很感激,如果有人能幫我設置來自我的API的正確價值。
謝謝, 奧利弗
class Company extends React.Component {
constructor(props){
super(props);
this.shortlink = this.props.shortlink;
this.company = null;
}
getCompanyByShortlink(shortlink){
//this works perfectly fine!
// return this.company = "test";
fetch('http://192.168.178.96:81/api/v1/companies/'+shortlink).then((response) => response.json())
.then((responseJson) => {
//this does not work for any reason.
return this.company = responseJson.data.company.company_name;
})
.catch((error) => {
console.warn(error);
});
}
render() {
this.company = this.getCompanyByShortlink(this.shortlink);
return (
<View style={styles.mainContainer}>
<Text style={styles.mainWelcome}>Your Company: {this.company} </Text>
</View>
);
}
};
'this.company = this.getCompanyByShortlink(this.shortlink);'將this.company設置爲'promise'而不是promise的解析值。 –