action分类
1)同步action
本质就是一个JS对象 这个对象中必须要包含一个属性叫type
{type:“INCREMENT”}
刚才写的加1减1案例,派发的都是同步action。
2)异步action
本质是一个函数,redux默认是处理不了异步action
异步action中第1个参数叫dispatch,第2个参数是getState
在异步action中就可以写异步代码
在异步代码,还需要派发一个同步的action
// 使用action creator创建一个异步action
export function incrementAsync(params) {
// 异步action中第1个参数叫dispatch,第2个参数是getState
return function(dispatch,getState) {
// 在异步action中就可以写异步代码
setTimeout(()=>{
// 在异步代码,还需要派发一个同步的action
dispatch(increment())
},3000)
}
}
对于异步的action来说,我们需要借助redux中间件来处理
先学一个:redux-thunk,它就可以处理异步action。
安装:npm i redux-thunk
如何使用redux中间件:
在 /store/index.js中
引入—>返回一个增强版的store—>重新定义仓库
import thunk from "redux-thunk"
// 返回一个增强版的createStore
let createStoreWithMiddleWare = applyMiddleware(thunk)(createStore)
let store = createStoreWithMiddleWare(reducer,composeEnhancers())
方式比较多,我们只需要掌握一种写法:
redux的中间件还是比较多的:
redux-thunk
redux-promise
redux-saga
redux-logger
redux-actions
解决跨域问题:
使用代理解决跨域
在src中创建setupProxy.js文件:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3000',
changeOrigin: true,
})
);
};
可以在package.json中配置代理: