[英]react-native fetch data from REST Api fails
I want to fetch data from a different Server with a REST API. 我想使用REST API从其他服务器获取数据。
I do this: 我这样做:
return fetch('http://localhost:9000/processes')
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(error);
});
In the render function I have this: 在渲染函数中,我有以下内容:
{JSON.stringify(getProcesses().Prozess1) }
and this 和这个
{JSON.stringify(getProcesses()) }
no one of thesse two examples returns something 这两个例子中没有一个返回任何东西
The rest API should return this: 其余的API应该返回以下内容:
{
"Prozess1": "Hallo ich bin ein Prozess"
}
whats my problem in this case 在这种情况下我的问题是什么
React render()
is a pure function of state
and props
. React render()
是state
和props
的纯函数。 You shouldn't try to perform asynchronous API calls or modify state inside render; 您不应尝试执行异步API调用或在render内部修改状态; so if you need to use fetched data in your components, you can either load it in the parent component and pass it as props
, or perform the fetch inside the component and save the result in your component state
. 因此,如果您需要在组件中使用提取的数据,则可以将其加载到父组件中并作为props
传递,也可以在组件内部执行提取并将结果保存为组件state
。
Here's an example of a possible, simplified implementation using the component 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>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.