使用react-redux做項(xiàng)目的時(shí)候遇到的一些問題

1、在前端請求ajax的時(shí)候會(huì)遇到跨域的問題,不能夠請求到數(shù)據(jù),需要搭建一下中間層,使用express來請求ajax數(shù)據(jù)然后前端再去請求后臺(tái)返回的數(shù)據(jù),這樣就不會(huì)遇到跨域問題,express代碼如下:


var ? express=require('express');

var ? router=express.Router();

var ? http=require('http');//引入http模塊

//后臺(tái)解決跨域問題

router.all('*',function(req,res,next) {

res.header("Access-Control-Allow-Origin","*");

res.header('Access-Control-Allow-Methods','PUT, GET, POST, DELETE, OPTIONS');

res.header("Access-Control-Allow-Headers","X-Requested-With");

res.header('Access-Control-Allow-Headers','Content-Type');

next();

});


// 輪播的接口

// localhost:3000/lunbo

router.get('/lunbo',function(req,res) {

varpage=req.query.page;

varcount=req.query.count;

// 要去請求? 賣座網(wǎng)的接口

// http://m.maizuo.com/v4/api/billboard/home?__t=1500253189212

vartime=newDate().getTime();

http.get('http://m.maizuo.com/v4/api/billboard/home?__t='+time,function(response) {

vardata='';

response.on('data',function(chunk) {

data+=chunk;

})

response.on('end',function() {

res.send(data);

})

})

})

2、上拉刷新的請求的ajax不能夠每次自動(dòng)加1的操作,后來做了監(jiān)聽滾動(dòng)事件的函數(shù),在生命周期里面進(jìn)行加1操作后在滾動(dòng)的時(shí)候再次請求ajax,當(dāng)滾動(dòng)的高度和當(dāng)前頁面高度進(jìn)行對比時(shí)候在去請求。代碼如下:

componentDidMount() {

window.addEventListener('scroll',this.handleScroll);

// var page = this.props.page

varthat=this;

$.get('http://localhost:8080/come_play?page='+page+'&count=7',function(res) {

if(res) {

vardata=JSON.parse(res).data.films;

that.props.getComeplay(data);

page++;

}

})

}

//獲取滾動(dòng)數(shù)據(jù)

handleScroll=()=>{

console.log(flag)

varlist=this.props.come_play;//獲取state的數(shù)據(jù)

varfilmes=[];//用來接收新的數(shù)據(jù)

varthat=this;//改變一下this指向

vartop=(document.documentElement.scrollTop||document.body.scrollTop)+50;//頁面的滾動(dòng)

console.log(top)

varheight=document.documentElement.clientHeight;

varnowheight=200+height*(page-3);

console.log(nowheight)

// console.log(height)

if(top>nowheight&&flag) {

flag=false;

$.get('http://localhost:8080/come_play?page='+page+'&count=7',function(res) {

if(res) {

vardata=JSON.parse(res).data.films;

varfilme=list.concat(data);

varset=newSet(filme);

filmes=newArray(...set);//數(shù)組去重

that.props.getComeplay(filmes);

flag=true;

}else{

flag=false;

}

})

page++;//頁數(shù)+1

}else{

flag=true;

}

}

//銷毀時(shí)

componentWillUnmount() {

window.removeEventListener('scroll',this.handleScroll);

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容