感谢react小书作者,看了三遍,对redux
有了点了解,写下随手笔记。
redux:
一、createStore
套路:
①、定义一个reducer
②、生成store
③、监听数据变化store.subscribe
④、首次渲染
⑤、随意dispatch
二、自己创建一个createStore
:
function createStore(reducer){
let state = null;
cosnt listeners = [];
const getState = () => state;
const subscribe = (listener) => listeners.push(listener)
const dispatch = (action) => {
state = reducer(state,action);//根据action更新state
listeners.forEach(listener => listener())
}
dispatch({}) //初始化state
return { getState, subscribe, dispatch };
}
三、创建reducer
function reducer(state,action){
if(!state){
return {} //初始化的state
}
switch(action.type) {
case "action.type1":
return {}
case "action.type2":
return {}
default:
return state
}
}
四、生成store
const store = createStore(reducer);
五、首次渲染
renderApp(store.getState())
六、监听数据变化
store.subscribe(()=>renderApp(store.getState()))
七、改变数据,引起页面重新渲染
store.dispatch({type:action.type1,color:red})
把store和context联系起来
一、把store存放于context中,这样每个子组件都可以拿到store了,
设置context方法:getChildContext { return {store}}
就把store设置到context上了
注意:getChildContext
必须配合childContextTypes
来校验store类型
但是context
是个危险的特性,除非你非常了解它,不然最后不要贸然使用,
所以我们需要一个高阶组件来专门于context
打交道,然后通过props的方式传递给Dumb组件
我们把这个高阶组件叫做 connect
,当dumb组件需要获取数据时,要按需获取,这样就需要我们告诉connect当前组件需要哪些数据和获取这些数据的方法,所以我们需要两个方法 mapStateToProps ``mapDispatchToProps
二、定义mapStateToProps
和 mapDispatchToProps
:
const mapStateToProps = (state) => {
return {
"color":state.color
}
}
const mapDispatchToProps = (dispatch) => {
return{
onChange:(color) => {
dispatch({type:'CHANGE_COLOR',color:color})
}
}
}
定义connect
用法:
HeaderComponent = connect(mapStateToProps,mapDispatchToProps) (HeaderComponent)
把存放store
这个操作用一个专门的组件来处理,这时我们就用到Provider
,并把它作为整个组件树的根组件,这样自己的store
和外部传入的store
都通过provider
来提供
这样就把所有的store
通过provider
原封不动的传给了每个需要的组件。
以上就是redux
,react-redux
工作的基本原理。实际项目中可以直接安装redux
和redux-react
,不必自己创建,以上笔记,到此结束。