这是我参与8月更文挑战的第4天,活动详情查看:8月更文挑战。
Redux-thunk介绍
redux-thunk 可以用来延迟action 的派发(dispatch), 这可以处理异步action的派发(dispatch)
安装
npm i --save-dev redux-thunk
1、在Reducers的index.js中使用applyMiddleware和redux-thunk
import {createStore,combineReducers,applyMiddleware} from 'redux'
import counterReducer from './count'
import thunk from 'redux-thunk'
import loginReducer from './user'
// 3. 存入仓库
let store = createStore(combineReducers({
counter: counterReducer,
user: loginReducer
}),applyMiddleware(thunk))
export default store
2、把之前同步的dispatch改成异步的,同时我们可以获取到所有的redux中的state
// this.props.dispatch(actions.counter.incCount({count: ++this.num}))
// 通过thunk发送
this.props.dispatch((dispatch,getState) =>{
dispatch(actions.counter.incCount({count: ++this.num}))
console.log(getState(),'获取方法...')
})
效果如下
二、Axios
1. axios的介绍
axios是一款基于promise封装的库, 可以运行在浏览器端和node环境中。vue官方开发组放弃了对其官方库vue-resource的维护,直接推荐我们使用axios。
1. 安装
npm i --save axios
2. axios的get请求在react中的使用
import axios from "axios";
componentDidMount() {
axios.get('http://vueshop.glbuys.com/api/home/index/nav?token=1ec949a15fb709370f')
.then(res => {
console.log(res,'数据...')
})
}
把数据渲染到页面
axios.get('http://vueshop.glbuys.com/api/home/index/nav?token=1ec949a15fb709370f')
.then(res => {
console.log(res,'数据...')
if(res.data.code === 200) {
this.setState({
navs: res.data.data
})
}
})
render中
<ul>
{
this.state.navs.map((v,i) => {
return (
<li key={i}>{v.title}</li>
)
})
}
</ul>
3. axios的post请求在react中使用
登录接口一般是x-www-form-urlencoded格式传参, 这是为了兼容IE, 我们可以使用urlSearchParams 也可以安装qs
let params = new URLSearchParams()
params.append('cellphone', this.state.username)
params.append('password', this.state.password)
axios.post('http://vueshop.glbuys.com/api/home/user/pwdlogin?token=1ec949a15fb709370f',params)
.then(res => {
if(res.data.code === 200) {
this.props.dispatch((dispatch)=>{
dispatch(actions.user.login( {username: this.state.username, isLogin: true}))
this.props.history.go(-1);
})
} else {
alert(res.data.data)
}
console.log(res)
})