redux和react-redux的简单使用
Redux
数据池管理工具
reducer(管理数据)
action(执行动作)
store(存储池)
创建存储池(使用reducer)
// 创建存储池
import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
rootReducers, // reducer
compose(
applyMiddleware(...[thunk]) // 使用的中间件数组
)
);
// 如果有多个reducer,使用combineReducers合并
import { combineReducers } from 'redux';
const rootReducers = combineReducers({
reducer1: reducer1,
reducer2: reducer2,
reducer3: reducer3
});
store(存储池)
// 执行动作
store.dispatch({type: 'action', payload: '数据'})
// 获取数据
store.getState()
reducer(数据管理器)
// 执行动作的执行器,state为数据,action为执行的动作(disptch传过来的对象),函数必须返回state
const (state, action) {/* */};
const reducer = (state, action) => {
switch(action.type) {
...
default:
return state;
}
}
action(执行动作)
const action = () => ({
type: '', // 在reducer中的case值
...otherParams
})
react-redux
连接react和redux的工具
connect(连接)
import React from 'react';
import { connect } from 'react-redux';
class Component extends React.Component {
constructor(props) {
super(props)
// 连接后props中就存在方法和数据
}
}
const mapStateToProps = (state, ownProps) => {
return { key: state.value }; // state为store中管理的数据
}
export default connect(mapStateToProps)(Component);