您好,登錄后才能下訂單哦!
這篇文章主要講解了“react如何請求數(shù)據(jù)異步”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“react如何請求數(shù)據(jù)異步”吧!
react請求數(shù)據(jù)異步的方法:1、通過“npm i redux-thunk --save npm i axios --save”命令下載thunk;2、在store.js里面引入thunk插件;3、在需要模塊的actionCreator里引入中間件“redux-thunk”即可。
react異步請求數(shù)據(jù)方法。
關(guān)于react異步請求數(shù)據(jù)有很多種方案。
1、saga (用了er6生成器函數(shù))
2、promise
3、thunk
4、…
為什么要用插件???是為了改造這個redux的action動作。如果異步的話,我們發(fā)動作,actionCreator只有返回對象,而異步這個插件能讓你隔一段時間再發(fā)這個動作,是為了改造動作用的。
本文用thunk,它可能不是最好的,但是是我用得比較習(xí)慣的。
一、下載
npm i redux-thunk --save
npm i axios --save
二、引用。在store.js里面引入插件,并使用。
import {createStore,applyMiddleware} from 'redux' //引入applyMiddleware
import reducers from './reducers' //總的reducer
import thunk from 'redux-thunk' //引入thunk
var store = createStore(reducer,applyMiddleware(thunk)); //使用中間件
export default store;
三、發(fā)數(shù)據(jù)
在你需要模塊的actionCreator里:
import axios from 'axios'
export default {
getData(){
return (dispatch)=>{ // 引入中間件redux-thunk后,就可以延遲發(fā)出動作
axios.get('http://www.xmyxapp.com/api/tab/1?start=0').then((res)=>{
console.log(res)
dispatch({
type:'GETDATA',
list:res.data.data.items.list
})
})
}
}
}
四、效果測試
在你需要的模塊里面的reducer:
var initState ={
list:[]
}
export const listReducer = (state = initState, action) => {
var newState ={...state};
switch (action.type) {
case 'GETDATA':
newState.list = action.list // 這個action.list就是該模塊actionCreator里傳過來的值
return newState;
default:
return state
}
}
在store里面總和的reducers:
import {combineReducers} from 'redux'
import {listReducer} from '../components/list/reducer'
var reducer = combineReducers({
list:listReducer
})
export default reducer;
在你需要的模塊里面的組件:
import React, { Component } from 'react'
import {connect} from 'react-redux'
import actionCreator from './actionCreator';
class List extends Component {
componentDidMount(){
this.props.getData(); // 調(diào)用異步方法獲取數(shù)據(jù)
}
render() {
console.log(this.props);
return (
<div>
<ul>
{
this.props.list.list.map((item)=>{
return item.title?<li key={item.id}>{item.title}</li>:""
})
}
</ul>
</div>
)
}
}
export default connect((state)=>state,actionCreator)(List);
感謝各位的閱讀,以上就是“react如何請求數(shù)據(jù)異步”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對react如何請求數(shù)據(jù)異步這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。