2017-04-10 7 views
0

REST APIを使用して別のサーバーからデータをフェッチしたいとします。私はこの持っているレンダリング機能でREST APIからのネイティブ・フェッチ・データが失敗する

return fetch('http://localhost:9000/processes') 
     .then((response) => response.json()) 
     .then((responseJson) => { 
      return responseJson; 
     }) 
     .catch((error) => { 
      console.error(error); 
     }); 

 {JSON.stringify(getProcesses().Prozess1) } 

をし、この

 {JSON.stringify(getProcesses()) } 

thesse二つの例の誰もが何か

を返し

私はこれを行います

T彼は、APIがこれを返すべきで休ま:この場合、私の問題は

+0

'getProcessesを()'非同期動作約束を返すことがありますか? – Sulthan

+0

はいgetProcesses ist関数shoukd jsonを返します – Felix

+0

fetch()は非同期なので、何も返さないでください。 fetch()。then()は約束です。これは、フェッチが完了するたびに次のことを行うことを意味します。だからあなたのコードを少しリファクタリング –

答えて

3

render()に反応いただきまし

{ 
    "Prozess1": "Hallo ich bin ein Prozess" 
} 

statepropsの純粋な関数です。非同期API呼び出しを実行したり、レンダリング内で状態を変更したりしないでください。したがって、コンポーネントでフェッチされたデータを使用する必要がある場合は、親コンポーネントにロードしてpropsとして渡すか、コンポーネント内でフェッチを実行し、結果をコンポーネントstateに保存します。

ここ成分state使用可能な、簡略な実装の例は次のとおり

class MyComponent extends Component { 
    constructor(props) { 
    super(props); 
    this.getProcesses = this.getProcesses.bind(this); 
    } 

    componentDidMount() { 
    this.getProcesses(); 
    } 

    async getProcesses() { 
    try { 
     const response = await fetch('http://localhost:9000/processes'); 
     if (response.ok) { 
     const processes = await response.json(); 
     this.setState({processes}); //this will trigger the render function with the new state 
     } else { 
     console.error(response.status); 
     } 
    } catch(e) { 
     console.error(e); 
    } 
    } 

    render() { 
    const {processes} = this.state; 
    return (
     <Text> 
     {processes && processes.Prozess1} 
     </Text> 
    ); 
    } 
} 
関連する問題