Ich mache eine einfache AJAX -Anforderung mit der Abruf-API in React, insbesondere in der Funktion componentDidMount()
.
Es funktioniert, weil die Konsole das Ergebnis zu protokollieren scheint. Ich weiß jedoch nicht, wie ich auf die Antwort zugreifen kann ...
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
Ich habe versucht, auf myData
außerhalb der Abrufmethode zuzugreifen, aber es wird ein Fehler ausgegeben, der besagt, dass es undefiniert ist. Es ist also nur im Rahmen der Funktion zugänglich.
Ich habe dann folgendes versucht:
.then(function(response) {
let myData = response.json()
// return myData;
this.setState({
data: myData
})
})
Dieses Mal bekomme ich Cannot read property 'setState' of undefined(…)
Wie kann ich die Abrufantwort an den Status oder sogar nur an eine globale Variable übergeben?
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;
Soweit ich sehen kann, gibt es zwei Probleme: response.json()
gibt ein Versprechen zurück, sodass Sie myData
nicht auf das Versprechen setzen möchten, sondern zuerst das Versprechen lösen und dann auf Ihre Daten zugreifen können.
Zweitens ist this
nicht innerhalb desselben Bereichs in Ihrer Abrufanforderung. Aus diesem Grund werden Sie undefiniert. Sie können versuchen, den Bereich von this
außerhalb des Abrufs zu speichern:
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 ist undefiniert, da Sie statt der Pfeilfunktion die klassische Funktionssyntax verwenden. Die Pfeilfunktion nimmt "dieses" Schlüsselwort aus der "übergeordneten" Funktion, eine klassische Funktion () {} erstellt ihr eigenes "dieses" Schlüsselwort. Versuchen Sie dies
.then(response => {
let myData = response.json()
// return myData;
this.setState({
data: myData
})
})
Sie sind mit this.setState
auf dem richtigen Weg. Allerdings ist this
nicht mehr im Kontext der Komponente, wenn Sie sie innerhalb der Funktion aufrufen, die die Antwort behandelt. Die Verwendung einer =>
-Funktion behält den Kontext von this
bei.
fetch(URL)
.then((res) => res.json())
.then((json) => this.setState({data: json}));
Ändern Sie die Art und Weise, wie Sie auf die Antwortdaten zugreifen, indem Sie anstelle der Funktion '=>' verwenden, um im selben Kontext zu sein.
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
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-DATEI Erstellen Sie eine Datei replymsg.json und fügen Sie den folgenden Inhalt ein. Der Host sollte auf dem lokalen Host wie folgt aussehen: http: //localhost/replymsg.json
{"status":"200ok","CurrentID":28,"msg":"msg successfully reply"}
Sie müssen den aktuellen Kontext an die Zielfunktion binden
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)
})