状态管理:相当于vue中的vuex
redux可以应用在任何项目中(vue/react),react-redux是专门给react用的
1.安装
npm install redux react-redux --save
使用redux
- 创建容器:createStore; 同时还需要把reducer传递进来
reducer记录了左右状态的修改信息(根据行为标识走不同的修改任务),修改容器中的状态信息
import {createStore} from 'redux';
let reducer=(state={a:0},action)=>{
//state:容器中原有的状态信息(如果第一次使用,没有原状态,给一个初始默认值)
//action:dispatch任务派发的时候传递的行为对象(这个对象必有一个type属性,是操作的行为标识,reducer就是根据这个行为标识来是被如何修改状态信息)
let {type}=action;//type行为标识,一个标识对应一个状态修改的方式
switch(type){
case TYPE1:
state={....state,a:state.a+1}
break;
case TYPE2:
state={....state,a:state.a+2}
break;
}
return state
}
let store=createStore(reducer);//----创建store----
- store中提供三个方法
dispatch:派发行为(传递一个对象,对象中有一个type属性),通知ruducer修改状态信息
subscribe:事件池追加方法
getState:获取最新的状态管理信息
- 修改store状态,并触发组件渲染的步骤
1.将创建的store当做属性传递给子组件
2.在组件中,触发dispatch函数,执行reducer来触发响应的操作
this.props.store.dispatch({type:'TYPE1'});
此时store中的状态经过dispatch触发reducer函数,store中的state已经被修改成新的state
3.其他组件获取store中的状态
let reduxState=this.props.store.getState() //返回值就是store中保存的状态,
this.setState({...reduxState})//可以使用setState修改组件状态使其 能绑定到jsx上,并触发组件重新渲染
4.向发布订阅事件池中追加一个方法:监听redux容器中的状态改变,状态改变重新渲染组件
this.props.store.subscribe(()=>{
let reduxState=this.props.store.getState();
this.setState({
...reduxState
})
})
工作流程(简单说明)
image首先,用户发出 Action。
store.dispatch(action);
然后,Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State 。
let nextState = todoApp(previousState, action);
State 一旦有变化,Store 就会调用监听函数。
// 设置监听函数
store.subscribe(listener);
listener可以通过store.getState()得到当前状态。如果使用的是 React,这时可以触发重新渲染 View。
function listerner() {
let newState = store.getState();
component.setState(newState);
}
工程化结构
image.png- 所有的关于redux的逻辑都放在单独的文件夹store中处理
- action-types文件作用是将action中的type尽心初始化、
export const VOTE_SUPPORT='VOTE_SUPPORT';
- action文件夹中的文件的作用是产出提供给dispatch的那个参数(action),action是一个对象,对象中包括type属性和其他可选状态,action里边的index是文件夹的入口,集成了其他的action的模块
import * as TYPE from '../action-types.js'
support(){
return {
type:TYPE.VOTE_SUPPORT,
}
},
- reducer文件的作用是包括所有的reducer管理器 ,reducer里边的index是文件夹的入口,用redux中提供的combineReducers函数集成了其他的action的模块
import * as type from "../action-types"
export default function vote(state={
n:0,
},action){
switch(action.type){
case type.VOTE_SUPPORT:
state={...state,n:state.n+1}
break;
}
return state
}
- index文件就是store的入口文件
import {createStore} from 'redux';
import reducer from './reducer'
let store = createStore(reducer)
export default store;
网友评论