优化使用Redux,让应用更高效
在react中修改全局state就是个同步的过程。
通过dispatch具体的类型,立刻改变state,和拉取服务端数据的过程是异步的。这个是dispatch没有具体结果
Redux异步
Redux Middleware
- Redux的插件机制,使得Redux默认的同步Action扩展支持异步Action
export function updateName(params) {
return {
type:'UPDATE_NAME',
payload: params
}
}
dispatch(updateName('云'))
异步
function queryUserInfo(params) {
return (dispatch, getState) {
fetch({
// ...
}).
then((res) => {
dispatch({
type:'FETCH_DATA_SUCCESS',
payload: res.data
})
})
}
}
1.applyMiddleware接收一系列插件。每个插件(middleware)都会以dispatch和getState作为参数,并返回一个函数。该函数会被传入下一个插件中,直到调用结束。
import {
createStore,
combineReducers, applyMiddleware,
} from 'redux';
// 处理异步的插件
import thunk from 'redux-thunk';
export default createStore(
combineReducers,
applyMiddleware(...[thunk, otherMiddleware])
);
Reducer起始,插件执行一遍收尾,改变Reducer
@/src/store/index.js
import { createStore, applyMiddleware } from 'redux';
// 处理异步数据的redux插件
import thunk from 'redux-thunk';
import reducers from '@/reducer';
export default createStore(
reducers,
applyMiddleware(thunk),
);
/src/actions/home/index.js
import * as types from '../mutation-types';
// 请求数据方法
export function queryName(params) {
return {
type: types.QUERY_GLOBAL_NAME,
payload: params,
};
}
// 改变数据方法
export function updateName(params) {
return {
type: types.UPDATE_GLOBAL_NAME,
payload: params,
};
}
// 异步请求数据
export function queryAsyncName(params) {
return (dispatch, getState) => {
setTimeout(() => {
console.log('getState', getState())
dispatch({
type: types.QUERY_GLOBAL_NAME,
payload: params,
});
}, 2000);
};
}
// 异步修改数据
export function asynUpdatecName(params) {
return async (dispatch) => {
setTimeout(() => {
// 异步操作中会执行同步操作的方法,只是延迟了。
dispatch(updateName(params));
}, 3000);
};
}
@/src/containers/home/index.jsx
/* eslint-disable react/no-unused-prop-types */
import React, { Component } from 'react';
// react 的类型检测
import PropTypes from 'prop-types';
import { updateName, queryAsyncName, asynUpdatecName } from '@/actions/home';
import { connect } from 'react-redux';
@connect(
(state) => state.homeReducer,
(dispatch) => ({
updateName: (params) => dispatch(updateName(params)),
queryAsyncName: (params) => dispatch(queryAsyncName(params)),
asynUpdatecName: (params) => dispatch(asynUpdatecName(params)),
})
)
export default class Home extends Component {
handleClick = () => {
const {
// updateName,
// queryAsyncName,
asynUpdatecName,
} = this.props;
// console.log(updateName);
asynUpdatecName('异步云');
};
render() {
const { homeName } = this.props;
return (
<div>
<div>{homeName}</div>
<button type='button' onClick={this.handleClick}>
更改
</button>
</div>
);
}
}
// react 的类型定义,类型声明,检测非常重要
Home.propTypes = {
homeName: PropTypes.string,
updateName: PropTypes.func,
queryAsyncName: PropTypes.func,
asynUpdatecName: PropTypes.func,
};
Home.defaultProps = {
homeName: '',
updateName: () => ({}),
queryAsyncName: () => ({}),
asynUpdatecName: () => ({}),
};