2016-05-16 5 views
1

私のレンダリング機能私は会社の名前を表示しようとしています。したがって、私はthis.companyに値company_nameを代入する関数getCompanyByShortlinkを呼び出します。私は応答をチェックし、必要なすべてのデータを含んでいるので、ここで問題はありません。返されたネイティブセットvarからフェッチ

これは機能しませんが、値は割り当てられません。私が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);' 'promise'ない約束の解決された値にthis.companyを設定しています。 –

答えて

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のコードがsyncとasyncをミックスしているという説明は役に立ちます。すなわち、OPの 'getCompanyByShortlink'は値を返しません、それは約束を返し、OPのコードはそれが値を返すと仮定します。 –

+0

ありがとう!私はそれを解決した! これはまた非常に役立ちます:https://facebook.github.io/react-native/docs/tutorial.html#render-a-movie 乾杯 –

0

私はよく分かりませんが、あなたのリターン・ステートメントは字句thisで返されます。最初は悪いプログラミング慣行です。 this.that = thatのように設定し、thatを返すことができます。あなたはまた、副作用を意味する可能性のあるリターン内の課題を設定しています。それはそれから来るかもしれない。誰かがこれに対して賛成している場合は、話してください!

0

値を表示するには、アプリケーションを再レンダリングするためにsetStateを設定する必要があります。あなたは

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

に電話をかけて、自分のrender()機能にもcomponentDidMount()代わりのrender()方法の内側に機能getCompanyByShortlink()への呼び出しを行うYour Company: {this.state.company}

を設定することができます。 renderメソッドはすべての状態の更新に対して呼び出されるので、コンポーネントに多くの機能を追加すると、複数回呼び出されることがあります。

あなたはいいですね。

関連する問題