Pau*_*000 5 javascript json response reactjs fetch-api
我正在使用React中的fetch API创建一个简单的AJAX请求,特别是在componentDidMount()函数中.
它正在工作,因为控制台似乎正在记录结果.但是,我不知道如何访问响应...
componentDidMount = () => {
let URL = 'https://jsonplaceholder.typicode.com/users'
fetch(URL)
.then(function(response) {
let myData = response.json()
return myData;
})
.then(function(json) {
console.log('parsed json', json)
})
.catch(function(ex) {
console.log('parsing failed', ex)
})
} // end componentDidMount
Run Code Online (Sandbox Code Playgroud)
我尝试myData在fetch方法之外访问,但是这会抛出一个错误,说它是未定义的.所以它只能在函数范围内访问.
然后我尝试了这个:
.then(function(response) {
let myData = response.json()
// return myData;
this.setState({
data: myData
})
})
Run Code Online (Sandbox Code Playgroud)
这一次,我明白了 Cannot read property 'setState' of undefined(…)
如何将获取响应传递给状态,甚至只传递全局变量?
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
}
}
componentDidMount() {
let URL = 'https://jsonplaceholder.typicode.com/users'
fetch(URL)
.then( (response) => {
let myData = response.json()
// return myData;
this.setState({
data: myData
})
})
.then( (json) => {
console.log('parsed json', json)
})
.catch( (ex) => {
console.log('parsing failed', ex)
})
console.log(this.state.data)
} // end componentDidMount
render() {
return (
<div className="App">
{this.state.data}
</div>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
Sta*_*oul 13
就我所见,你有两个问题,response.json()返回一个承诺,所以你不想设置myData承诺,而是首先解决承诺,然后你可以访问你的数据.
其次,this在你的获取请求中不在同一范围内,这就是你未定义的原因,你可以尝试保存this外部获取的范围:
var component = this;
fetch(URL)
.then( (response) => {
return response.json()
})
.then( (json) => {
component.setState({
data: json
})
console.log('parsed json', json)
})
.catch( (ex) => {
console.log('parsing failed', ex)
})
console.log(this.state.data)
Run Code Online (Sandbox Code Playgroud)
setState未定义,因为您使用经典函数语法而不是箭头函数.箭头函数从'parent'函数中获取'this'关键字,经典函数(){}创建它自己的'this'关键字.试试这个
.then(response => {
let myData = response.json()
// return myData;
this.setState({
data: myData
})
})
Run Code Online (Sandbox Code Playgroud)
您走在正确的轨道上,this.setState但是this当您在处理响应的函数中调用它时,它不再位于组件的上下文中。使用=>函数维护 的上下文this。
fetch(URL)
.then((res) => res.json())
.then((json) => this.setState({data: json}));
Run Code Online (Sandbox Code Playgroud)