react-native - 获取数据反应原生
问题描述
如果有人问过这个问题,我很抱歉,我在反应原生方面是全新的......
我有一个简单的应用程序,它正在呈现一些类别,数据在一个带有数组的对象的 js 文件中:
export default tabs = {
categories: [
{ id: 'sample', title: 'sample' },
{ id: 'sample2', title: 'sample2' },
],
deals: [
{ id: 'sample', title: 'sample' },
{ id: 'sample2', title: 'sample2' },
],
};
我想使用同一个文件来连接 API 并获取数据。
我尝试了很多类似的东西:
import React from 'react';
const APIcategories = '......';
export default {
componentDidMount() {
console.log('inside... ');
fetch(APIcategories)
.then((res) => res.json())
.then((json) => this.setState({ data: json }));
},
};
它只是从来没有在日志中得到任何东西......尝试了许多其他方法没有......
任何人都有类似的东西
提前欣赏!
到目前为止我没有错误地管理:
import React, { Component } from 'react';
const APIcategories = 'https://.......';
class SomeClass extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
error: null,
};
this.arrayholder = [];
}
componentDidMount() {
this.someGetRequest();
}
someGetRequest = () => {
console.log('inside------');
fetch(APIcategories)
.then((res) => res.json())
.then((json) =>
this.setState({ data: res.results, error: res.error || null })
);
this.arrayholder = res.results;
console.log(arrayholder);
};
}
console.log('File opened---------');
export default SomeClass;
解决方案
创建一个类,然后实际使用它的方法..
class SomeClass extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
error: null,
};
this.arrayholder = [];
}
componentDidMount() {
this.someGetRequest();
}
someGetRequest = () => {
const url = `https:...`;
this.setState({ loading: true });
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
data: res.results,
error: res.error || null,
loading: false,
});
this.arrayholder = res.results;
console.log(res.results)
})
.catch(error => {
this.setState({ error, loading: false });
});
};
export default SomeClass;
此代码已使用 expo-cli 3.18.4 进行了测试
推荐阅读
- tensorflow.js - Tensorflow.js 预测不一致,返回 0 或按预期工作
- qt - QTabWidget 中的 QOpenGLWidget 减慢 MouseMoveEvent
- c# - how can i call a button click method from another class
- javascript - 我怎样才能得到一个 img 作为一个按钮?
- javascript - 为点击功能选择多个 div
- android - 混淆android API
- android - 从最近清除应用程序时如何处理作为前台运行的服务?
- scala - 模棱两可的隐含值:匹配预期类型cats.derived.MkShow[A]:显示猫:小猫
- arrays - 如何更新 MongoDB 中的多级嵌套数组?
- python - 使用 tf.train 时带有 tf.dataset 的 Keras model.fit() 工作正常