笔记15Redux使用总结

Redux使用总结



Redux简介:redux是一个用于解决组件间状态共享问题的,集中管理状态的应用数据流框架

流程:组件调用store的dispatch,触发actionCreator,携带store中的旧state与action(action.type,action.payload)流入reducer,返回新的state,用户组件通过getState方法来获取新的状态

Redux注意事项


1、单一数据流:整个应用的state被存储在一颗object tree中,并且它只存在于唯一的一个store中;


2、state是只读的:state作为redux的状态存储,改变state的方法就是通过触发action,流入reducer,来返回新的状态;


3、Reducer是一个纯函数:它接收一个对象,action和state,返回一个新的state;纯函数意义在于返回值只依赖于输入值,而不会发生意外操作。


4、redux是同步的,如果想在action里进行异步ajax请求,可以使用react中间件如redux-thunk。中间件作为action和state之间的桥梁,封装dispatch,让我们可以在action中封装对应承载了异步ajax操作的函数。实现redux中的数据请求等功能。



Action

    Action是把数据从应用传到store的有效载荷。它是store数据的唯一来源。
一般来说你会通过store.dispatch()来将action传入到store

Reducer

    Reducers指定了应用状态的变化是如何响应action并发送到store的,
记住action只是描述了有state更新的发生,而没有描述应用如何更新state

Store

    Store维持应用的状态,提供getState方法来让应用(组件)获取state,
提供了dispatch方法来更新state,subscribe(listener)来注册监听器

使用实践
  1、组件中:通过@connect连接redux:
   @connect( ({ReducerName}) => ({ReducerName}) ,
               (dispatch)=>({dispatchRename(data){
               //若在action使用store.dispatch提交动作,则此处可不写,
而是组件中直接调用action方法 dispatch(actionName(data)) }, }) ) 2、Store区域,用redux-thunk做中间件,使用createStore创建store并向外暴露store 3、组件中使用方法、属性:通过connect连接redux, 调用属性如this.props.reducerName.属性; 调用方法如this.props.actionName.方法名;(若在action中 使用getStore获取store实例,并使用store.dispatch写法, 则此处可以直接调用action中封装的方法而加'this.props') 4、action中对于dispatch的封装,(实例:上拉加载功能) export const getFeedbackList = (page=0,page_num=10)=>{ const store = getStore(); setLoading(true)//开始上拉加载 get('API',{param},true) .then((res)=>{ const {...} = res; if(code != 200){...;return} store.dispatch({ type: ABC, data:{ aaa: data.aaa, bbb: data.bbb } }) setLoading(false) }).catch(()=>{ setLoading(false) }) } 5、Reducer状态处理: export default function feedbackList (state = INITIAL_STATE,action={}){ const {type ,data={}} = action const {...} = data if(type === TYPE1){ return {...state, aaa:新的aaa, bbb:新的bbb} } else if (type === TYPE2){...} else {return state} } 6、应用中触发action handleScroll = ()=>{ const {...} = this.props.reducerName const {...} = this.state //进行触发的一些判断操作如是否还有数据、节流等(略) this.props.actionName(data) //触发上拉加载的action }