2017-06-07 6 views
1
import Request from 'superagent'; 

const getApi =() => { 
    let url = '/* URL */'; 
    return Request.get(url).then((res) => { 
     this.setState({ 
      content: res.body 
     }); 
    }); 
} 

export default getApi; 

の外部ファイルにfunctionを作成しました。 function/setStateへの外部ファイルへのアクセス方法を教えてください。外部関数でsetStateを使用するには?

componentWillMount(){ 
    getApi(); 
} 

私はこのエラーが表示されます。

'TypeError: Cannot read property 'setState' of undefined'

+0

[どのように応答を返さないのが重複する可能性非同期呼び出しから?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

+1

'getApi()'メソッドに 'コールバックメソッド'を渡し、レスポンスを取得したらそのメソッドを呼び出し、そのコールバックメソッド内でsetStateを実行します。 –

+1

あなたは応答を返してから関数にsetStateを返す必要があります –

答えて

0

マイソリューション:

function getApi(component) { 
     let url = '/* url */'; 
     return Request.get(url).then((res) => { 
      component.setState({ 
       content: res.body, 
      }); 
     }); 
    } 

componentWillMount(){ 
    getApi(this); 
} 
2

あなたのコンポーネントからgetApi関数にコールバックを渡すことができます。

const getApi = (onSuccess) => { 
    let url = '/* URL */'; 
    return Request.get(url).then((res) => { 
     onSuccess(res.body); 
    }); 
} 

コンポーネント

componentWillMount(){ 
    getApi(this.setApiResponse); 
} 

setApiResponse(data) { 
    this.setState({ 
     content: data 
    }); 
} 

NB。プロジェクトが大きくなるにつれ、Reduxなどの状態管理システムを調べることをお勧めします。

1

に技術的に渡して、thisとなるはずです。しかし、イモ。それは貧弱なアプローチです。不要な依存関係が作成されます。現時点では、getApi()はReactクラスの仕組みを知る必要があります。この関数はインスタンスの状態を正しく操作する責任があります。

getApi()のみ値を返し、インスタンスがそれを消費した場合より良い:

const getApi =() => { 
    let url = '/* URL */'; 
    return Request.get(url).then(res => res.body); 
} 

componentWillMount(){ 
    getApi().then(content => this.setState({ content })); 
} 
関連する問題