[英]How to handle fetch API AJAX response in React
我正在使用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
我嘗試在fetch方法之外訪問myData
,但這會拋出一個錯誤,說明它是未定義的。 所以它只能在函數范圍內訪問。
然后我嘗試了這個:
.then(function(response) {
let myData = response.json()
// return myData;
this.setState({
data: myData
})
})
這一次,我得到了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;
就我所見,你有兩個問題, response.json()
返回一個promise,所以你不想將myData
設置為promise,而是首先解析promise,然后你可以訪問你的數據。
其次, 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)
setState未定義,因為您使用經典函數語法而不是箭頭函數。 箭頭函數從'parent'函數中獲取'this'關鍵字,經典函數(){}創建它自己的'this'關鍵字。 試試這個
.then(response => {
let myData = response.json()
// return myData;
this.setState({
data: myData
})
})
你是在正確的軌道上this.setState
但是this
不再當你調用它的函數處理響應中的組件的上下文。 使用=>
功能保持的上下文this
。
fetch(URL)
.then((res) => res.json())
.then((json) => this.setState({data: json}));
REACT NATIVE
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
} from 'react-native';
export default class SampleApp extends Component {
constructor(props) {
super(props);
this.state = {
data: 'Request '
}
}
componentDidMount = () => {
fetch('http://localhost/replymsg.json', {
mode: "no-cors",
method: "GET",
headers: {
"Accept": "application/json"
},} )
.then(response => {
if (response.ok) {
response.json().then(json => {
console.warn( JSON.stringify(json.msg ));
this.setState({
data: JSON.stringify(json)
})
});
}
});
}
render() {
return (
<Text> {this.state.data}</Text>
);
}
}
AppRegistry.registerComponent('SampleApp', () => SampleApp);
JSON FILE創建一個文件replymsg.json並放在內容之下,它應該托管到本地主機,如: http://localhost/replymsg.json
{"status":"200ok","CurrentID":28,"msg":"msg successfully reply"}
使用“=>”而不是函數在同一上下文中更改訪問響應數據的方式。
componentDidMount = () => {
let URL = 'https://jsonplaceholder.typicode.com/users'
fetch(URL)
.then(function(response) {
let myData = response.json()
return myData;
})
.then((json) => {
console.log('parsed json', json)
})
.catch(function(ex) {
console.log('parsing failed', ex)
})
} // end componentDidMount
您需要將當前上下文綁定到目標函數
fetch(URL)
.then(function(response) {
return response.json();
})
.then(function(json) {
this.setState({data: json})
}.bind(this))
.catch(function(ex) {
console.log('parsing failed', ex)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.