reactjs - 如何将 API 数据返回到单独的组件 - React Native
问题描述
我正在从本机应用程序中的 API 获取数据并将其显示为列表。
下面是我的代码:
async componentWillMount() {
if (Platform.OS === 'android') {
BackHandler.addEventListener('hardwareBackPress', this.backPressed);
}
this.fetchNotifications();
}
}
async fetchNotifications() {
this.setState({refreshing: true});
const config = getAppConfig();
const cognitoToken = await this.getCognitoToken(config);
if (cognitoToken !== null) {
let headers = await this.getRequestHeaders(cognitoToken);
let body = this.getRequestBody(config);
let notificationUrl = config["notification-retrieve-api"];
return fetch(notificationUrl,
{
method: 'POST',
headers: headers,
body: body
}).then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong');
}
})
.then((notifications) => {
console.log(JSON.stringify(notifications));
this.setState({
notifications,
error: null,
refreshing: false
});
}).catch((error) => {
this.setState({
notifications: [],
error,
refreshing: false
});
});
}
}
这工作正常。我可以从 API 中检索数据。
现在我想将 API 代码与我的屏幕组件分开。我将在我的屏幕组件中调用“fetchNotifications”作为一个函数。我正在尝试这样做,但它根本不起作用。
这就是我正在做的事情:
async componentWillMount() {
if (Platform.OS === 'android') {
BackHandler.addEventListener('hardwareBackPress', this.backPressed);
}
let response = fetchNotifications();
this.setState({
notifications: response,
error: null,
refreshing: false
})
}
}
async function fetchNotifications() { //now this function is in another component
.
.
.
.
if(cognitoToken !== null) {
let headers = await this.getRequestHeaders(cognitoToken);
let body = this.getRequestBody(config);
let notificationUrl = config["notification-retrieve-api"];
return fetch(notificationUrl,
{
method: 'POST',
headers: headers,
body: body
}).then((response) => {
if (response.ok) {
response.json();
} else {
throw new Error('Something went wrong');
}
})
.then((response) => {
return response;
}).catch((error) => {
this.setState({
notifications: [],
error,
refreshing: false
});
});
}
}
export default fetchNotifications;
这种方式正确吗?谁有更好的解决方案?
解决方案
我的两分钱,我总是把异步任务放在里面Promise
,包括 API 请求。
// API helper file
export const fetchNotifications = (params) => {
return new Promise(async (resolve, reject)=>{
try{
const headers = getHeaders(params)
const body = getBody(params)
const response = await fetch(notificationUrl,
{
method: 'POST',
headers: headers,
body: body
})
if (response.ok) {
const responseObj = await response.json();
resolve(responseObj)
} else {
throw new Error('Something went wrong');
}
} catch (e) {
// something went wrong
generalHandler(e) // logging etc.
reject(e) // for ui handling
}
}
}
然后我们可以在任何地方使用它
import { fetchNotifications } from '.../APIHelper'
在您的 ui 文件中:
componentWillMount() {
fetchNotifications(params)
.then((notifications) => {
console.log(JSON.stringify(notifications));
this.setState({
notifications,
error: null,
refreshing: false
});
}).catch((error) => {
this.setState({
notifications: [],
error,
refreshing: false
});
});
}
推荐阅读
- powershell - 在脚本中获取随机的“InputObject”验证错误
- macos - 在 m1 macbook air 上安装带有 Ubuntu 16 的 VM
- java - 在 ConstraintLayout 中设置对讲顺序
- javascript - 未应用反应组件中的切换 css
- machine-learning - ML.net 中多类多标签分类的每类加权损失
- android - 如何将意图额外传递给 SingleInstance 类 Android
- r - 如何重塑宽汇总表?
- javascript - 当标签键与过滤键不同时,异步自动完成不显示选项
- java - 我不知道如何使用 Project Reactor 的 then 运算符
- jquery - 传递给 Symfony\Component\HttpFoundation\Response::setContent() 的 TypeError 参数 1 必须是字符串类型或 null,给定对象,