加載之初需要我們從后臺(tái)獲取數(shù)據(jù)斜友。
沒有后臺(tái)的情況下可以用node.js做模擬服務(wù)器:
在項(xiàng)目下/public/test/api中新建data.json文件
建在public里面是因?yàn)樵撐募粎⑴c構(gòu)建和打包
src里面的文件參與構(gòu)建
使用nodejs開發(fā)的一個(gè)服務(wù)器serve,初次使用的話應(yīng)該是沒有的,安裝一個(gè)
$npm install -g serve
cd XXX/public/test/
$serve
顯示:
打開瀏覽器訪問localhost:5000/api/data.json便能獲取
打開另一個(gè)cmd啟動(dòng)我們的react項(xiàng)目
在react組件掛載階段中垃它,像 Ajax 數(shù)據(jù)的拉取操作鲜屏、一些定時(shí)器的啟動(dòng)等,就可以放在 componentWillMount 里面
安裝fetch
$npm install whatwg-fetch --save
npm install es6-promise --save
組件中引用并應(yīng)用:
import 'whatwg-fetch'
...
componentWillMount (){
fetch(“l(fā)ocalhost:5000/api/data.json”)
.then(response => response.json())
.then(json => {
console.log('i get'+json)
})
.catch(e => {
console.log('服務(wù)器報(bào)錯(cuò)'+e)
})
}
報(bào)錯(cuò)国拇,3000端口訪問5000端口屬于跨域
在 packager.json中添加“proxy”屬性:
"proxy": {
"/api": {
"target": "http://192.168.31.1:5000"
}
}
不寫localhost://5000是因?yàn)檫@種寫法時(shí)好時(shí)壞
cmd重啟項(xiàng)目
報(bào)錯(cuò)原因是配置項(xiàng)中的“react-scripts”版本過高洛史,重裝一下1.1.1版本的
$npm install react-scripts@1.1.1
cmd重啟項(xiàng)目,好了酱吝。接口我們改一下:
fetch(“/api/data.json”)也殖。。务热。
獲取正常。
網(wǎng)上說react-thunk的引用場(chǎng)景是fetch加載數(shù)據(jù)崎岂,loading加載等捆毫。。不用react-thunk也能做到啊冲甘。绩卤。
那對(duì)我來說,react-thunk的作用是:
dispatch一個(gè)函數(shù)
一般來說dispatch接受一個(gè)對(duì)象作為參數(shù)江醇,reducer通過switch對(duì)象的type命來啟動(dòng)操作
但當(dāng)我們需要觸發(fā)多dispatch邏輯應(yīng)用時(shí)省艳,一般我都當(dāng)作請(qǐng)求數(shù)據(jù)時(shí)的公共方法在用:
import {toggleloading,togglemsg} from '../redux/action/layer'
export const fetchPosts = (postTitle,Fn) => (dispatch, getState) => {
dispatch(toggleloading(true));//加載loading
return fetch(postTitle)
.then(response => response.json())
.then(json => {
setTimeout(()=>{
dispatch(toggleloading(false));//關(guān)閉loading
return Fn(json);//回調(diào)函數(shù)處理結(jié)果
},1000)
})
.catch(e => {
dispatch(toggleloading(false));
dispatch(msgFn('服務(wù)器報(bào)錯(cuò)'))
})
}
這個(gè)dispatch中傳入了一個(gè)函數(shù)哦辐烂,那如何讓dispatch接受一個(gè)函數(shù)作為參數(shù)呢捂贿?
react-thunk派上了用場(chǎng):
import rootReducer from './reducer';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
let store = createStore(
rootReducer,
applyMiddleware(thunk)
);
export default store;
你的store需要加點(diǎn)applyMiddleware(thunk)厂僧,此時(shí)thunk作為中間件辰妙,這個(gè)applyMiddleware作為中間件數(shù)組粗井,還可以放其他尔破,注意日志中間件要放在最后。
在組件中如何應(yīng)用呢胆剧?
import {fetchPosts} from '../../lib/common'
。。匿垄。
componentWillMount(){
// this.props.toggle_msg('iam comi!!!');
this.props.fetchPosts('/api/data.json',(res)=>{
this.props.getgoodlist(res.data.songs);
})
}
前提是在mapDispatchToProps中聲明該方法:
const mapDispatchToProps = (dispatch) =>({
fetchPosts:(url,fn)=>dispatch(fetchPosts(url,fn))
})