[英]I cannot correctly consume a json response in React/Axios
我在处理来自打开的 api 的 json 响应时遇到问题。 有问题的响应如下所示: http://geodb-free-service.wirefreethought.com/v1/geo/cities?namePrefix=london我的代码在这里: https://codesandbox.io/s/st01-r803
我尝试了一些不同的东西,但我无法弄清楚如何正确使用它,正如您在控制台日志中看到的那样。 谢谢您的帮助。
您获取 function 是正确的。 为什么您在console.log
中看不到正确的 output 是因为setState
在 React 中是异步的,因此对 state 的更改不会立即反映出来。 您需要在此处为setState
使用回调 function :
test() {
axios
.get(
`geodb-free-service.wirefreethought.com/v1/geo/cities?namePrefix=london`
)
.then(res => {
this.setState({
locationdata: res.data
}, () => { // Use callback function
console.log(this.state.locationdata);
});
});
}
刚刚更改了您的 api 并且它正在工作。 您的 api 有 http 请求。
import React from "react";
import axios from "axios";
class alex extends React.Component {
constructor(props) {
super(props);
this.state = {
daten: null,
locationdata: null
};
this.test = this.test.bind(this);
}
componentDidMount() {}
test() {
axios.get(`https://jsonplaceholder.typicode.com/photos`).then(res => {
this.setState({ locationdata: res.data });
console.log(this.state.locationdata[0]);
});
}
render() {
return (
<div>
<br />
<button type="submit" onClick={this.test}>
Halleluha
</button>
<br />
</div>
);
}
}
export default alex;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.