0
我製作滑塊,並得到錯誤 - 第一次點擊下一張幻燈片,只獲取數據和計數items.length像0.然後第二次點擊幻燈片。如何計算APIRequest後的項目長度(240 *(items.length - 4)* -1)。似乎需要承諾,但即使我找到解決方案,然後檢查數據是否已加載並且不再加載。請幫我瞭解並找到該任務的解決方案..阿賈克斯在反應後計數
import React, { Component } from 'react';
import 'whatwg-fetch';
import Journal from './Journal';
export default class JournalsGroup extends Component {
state = {
items: [],
left: 0,
loaded: false
}
componentDidMount(){
//if !this.props.data
this.APIRequest(this.props.id);
}
slide = (dir) => {
let { left, items, loaded } = this.state;
if(!loaded){
this.APIRequest(this.props.id, true);
this.setState({loaded: true});
}
if(left < 0 && dir === 'left'){
this.setState({left: left + 240});
}
//todo: count items only after ajax
if (left < 240 * (items.length - 4) * -1 && dir === 'right'){
this.setState({left: left - 240});
}
}
APIRequest = (id, all) => {
const myHeaders = new Headers();
myHeaders.append('X-User-Agent', '');
const myInit = { method: 'GET',
headers: myHeaders
};
let myRequest;
if(this.props.magazine){
myRequest = new Request(`magazines/${id}/issues?limit=4`,
myInit);
}else {
myRequest = new Request(`catalog/category/${id}/issues?limit=${this.props.main ? 8 : 4}`,
myInit);
//todo: pagination
if(all){
myRequest = new Request(`catalog/category/${id}/issues`,
myInit);
}
}
if(this.props.all){
myRequest = new Request(`catalog/category/${id}/issues`,
myInit);
}
if(!!this.props.data){
this.setState({items: this.props.data});
} else {
fetch(myRequest)
.then(response => {
return response.json();
})
.then(data => {
this.setState({items: data.data});
if(all){
this.setState({loaded: true});
}
})
.catch(console.log);
}
}
render() {
}
爲什麼你給回調的API請求的功能,當你可以輕鬆地返回的承諾,讓上(主叫)函數處理的承諾。否則,我們會在回調地獄結束,我們生活在Promises存在之前。 – Kyon
謝謝你的改進。我更新了我的答案。現在看起來好嗎? – bennygenel
方式更好,謝謝,先生! – Kyon