2017-04-10 32 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他REST API应该返回此:

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

什么我在这种情况下,问题

+0

'getProcesses()'是异步操作,它返回一个承诺? – Sulthan

+0

是getProcesses ist函数返回json – Felix

+0

fetch()是异步的,所以它不应该返回任何东西。 fetch()。then()是一个承诺,这意味着每当读取完成时,执行以下操作。所以重构一下你的代码 –

回答

3

阵营render()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> 
    ); 
    } 
}