来自 REST Api 的反应本机获取数据失败
react-native fetch data from REST Api fails
我想使用 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()) }
这两个例子中没有一个return有点东西
其余API应该return这个:
{
"Prozess1": "Hallo ich bin ein Prozess"
}
在这种情况下我的问题是什么
React render()
是 state
和 props
的纯函数。您不应该尝试在渲染中执行异步 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>
);
}
}
我想使用 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()) }
这两个例子中没有一个return有点东西
其余API应该return这个:
{
"Prozess1": "Hallo ich bin ein Prozess"
}
在这种情况下我的问题是什么
React render()
是 state
和 props
的纯函数。您不应该尝试在渲染中执行异步 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>
);
}
}