Redux中文文档
npm install --save redux
store(仓库)存放整个应用的state。
创建仓库
import { createStore } from 'redux';
import reducer from './store/reducer';
let store = createStore(reducer)
//createStore还有第二个参数,表示State的最初状态或者是一个中间件
getState获取状态
const state = store.getState()
描述事件的简单对象,改变state需要触发action。
ActionType:
export const INCREAMENT = 'num';
export const ADD_COUNTER= 'add';
Action
import { INCREAMENT, ADD_COUNTER} from './ActionType';
const actionType = {
return {
type: INCREAMENT
}
}
export function Add(num) {
return {
type: ADD_COUNTER,
payload: num
}
}
action描述的事件需要dispatch来触发。它将action发送到reducer函数中。
store.dispatch(actionType)
action只是描述事件的对象,dispatch触发了动作通知更新state,reducer更新。reducer是一个纯函数。
import { INCREAMENT, ADD_COUNTER} from './ActionType';
const initState = {count: 0}
export default function MyReducer(state = initState, action) {
switch (action.type) {
case INCREAMENT:
return { ...state, count: state.count + 1 }
case ADD_COUNTER:
return { ...state, count: state.count - action.payload }
default:
return state
}
}
一旦state发生变化,就会自动执行这个函数。
store.subscribe(()=>{
console.log('state发生了变化:',store.getState().count)
})
合并Reducer。
将所有的中间件组成一个数组,依次执行。
中间件就是一个函数,对store.dispatch方法进行改造,在action和reducer中间添加其他功能。
如果要在react中使用redux则需要react-redux,它将组件分为容器醉组件和展示组件。
容器组件获取数据更新状态,展示组件呈现UI。
npm install --save react-redux
提供者,将store作为props放到context中,让所有子组件拿到state。
import { createStore } from 'redux';
import { Provider } from 'react-redux'
let store = createStore(reducer);
connect方法使得UI组件可以直接通过props拿到容器组件上的所有属性和方法了。
import { connect } from 'react-redux';
export default connect(mapStateToProps, mapDispatchToProps)(App);
创建传入的state到UI组件中props的映射关系。
订阅Store,每当state更新的时候就会自动执行,重新渲染UI组件。
let mapStateToProps = (state) => {
return { totalCount: state.count }//state这里拿到Store里的state
}
用来建立UI组件的参数到store.dispatch方法的映射。
import { Add, Sub } from './store/ActionCeator'
const mapDispatchToProps = (dispatch) => {
return {
add1: (num) => dispatch(Add(num)),
sub: (num) => dispatch(Sub(num))
}
}
由于reducer中只能写纯函数,所以在处理一些异步操作的时候需要使用中间件。
默认情况下action是一个对象,使用redux-thunk之后action也可以是一个函数。
redux中间件redux-thunk的作用_徐同保的专栏-CSDN博客_redux-thunk