2016-05-16 49 views
1

我試圖顯示公司的名稱。因此我調用了一個函數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> 
    ); 
} 

};

+0

'this.company = this.getCompanyByShortlink(this.shortlink);'將this.company設置爲'promise'而不是promise的解析值。 –

回答

2

你不應該在渲染功能中做異步操作。試試這個方法:

class Company extends React.Component { 
    constructor(props){ 
    super(props); 
    this.shortlink = this.props.shortlink; 

    this.state = { 
     company: null 
    }; 

    this.getCompanyByShortlink(this.shortlink).then((company) => { 
     this.setState({company}); 
    }); 
    } 

    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().data.company.company_name) 
     .catch((error) => console.warn(error)); 
    } 

    render() { 
    return (
     <View style={styles.mainContainer}> 
     <Text style={styles.mainWelcome}>Your Company: {this.state.company} </Text> 
     </View> 
    ); 
    } 
} 
+0

是的強制重新渲染的正確方法是通過設置狀態。除此之外,OP的代碼混合同步和異步的解釋會有所幫助。也就是說,OP的'getCompanyByShortlink'不返回一個值,它返回一個承諾,OP的代碼假定它返回一個值。 –

+0

非常感謝!我解決了它! 這也是非常有用的:https://facebook.github.io/react-native/docs/tutorial.html#render-a-movie 乾杯 –

0

我不確定,但是您的退貨聲明是返回一個詞彙this,首先我的意思是糟糕的編程習慣。你可以設置類似this.that = that然後返回that。你也在回報裏面設置一個可能意味着副作用的任務。它可能來自於此。如果有人對此有利,請說出來!

0

你需要設置狀態來重新渲染應用程序來顯示值。您可以撥打

this.setState({ company: responseJson.data.company.company_name})

,並在您render()功能設置Your Company: {this.state.company}

而且使調用函數getCompanyByShortlink()componentDidMount()而不是render()方法裏面。因爲每個狀態更新都會調用render方法,所以在爲組件添加更多功能時可能會多次調用render方法。

你會很開心。