我正在做一个react原生项目,其中我试图检索一个json对象数组。我目前使用的fetch函数如下:
//******************* require in root App.js ***********
global.fetch = require('isomorphic-fetch');
//******************* API.js *************************
import fetch from 'isomorphic-fetch';
const api = {
getData() {
const url = 'http://.php?route=users';
return fetch(url).then((res) => res.json());
}
};
export { api };
//****************** dataRetrieval.js *********************
//imports
import api.js form './filepath.js';
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
error: '',
loading: false,
users: []
};
}
componentDidMount() {
api.getData(this).then((res) => {
this.setState({ users: res.getData });
});
}项目依赖关系:
"dependencies": {
"axios": "^0.18.0",
"eslint-config-rallycoding": "^3.2.0",
"isomorphic-fetch": "^2.2.1",
"node-fetch": "^2.2.0",
"npm": "^6.4.1",
"react": "16.4.1",
"react-native": "0.56.0",
"react-native-fetch": "^2.0.0",
"react-navigation": "^2.12.1",
"unfetch": "^3.1.1"
},当我尝试运行模拟器时,我收到一个错误,指出我的getData()函数未定义,无法读取。
发布于 2018-11-09 14:11:56
您错误地使用了export/import。
在API.js文件中使用export default api,或在dataRetrieval.js文件中使用import { api } from './filepath.js'。
发布于 2018-11-09 15:46:47
然后,加上上面的答案,你应该编写.catch。这与你的错误无关,但必须养成习惯。
import fetch from 'isomorphic-fetch';
const api = {
getData() {
const url = 'http://.php?route=users';
return fetch(url)
.then((res) => res.json())
.catch(err=> console.log(err)
}
};您可以检查this
https://stackoverflow.com/questions/53220032
复制相似问题