关于redux的理解

创建redux

import {createStore} from 'redux'
const  store = createStore(reducer)

其中reducer 是执行者,负责改变 state 的状态

const state ={
}

state 存储状态 通过 store.getState() 获取当前的state

state改变引起视图改变

const action = {
  type: 'ADD_TODO',
  payload: 'Learn Redux'
};

state发生改变,发起一个动作(action)

store.dispatch()

通过dispatch 发送通知告诉执行者

执行者 Reducer

执行者收到通知 改变state
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。

const reducer = function (state, action) {
  
  return new_state;//新的state
};

createStore接受 Reducer 作为参数,生成一个新的 Store。以后每当store.dispatch发送过来一个新的 Action,就会自动调用 Reducer,得到新的 State

subscribe 监听函数

Store 允许使用store.subscribe方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。

store.subscribe(listener);
function listener(){
//可以是react 中的render 函数  渲染view
//  可以是 setstate  改变 state值
}

版权声明:本文为qq_39454316原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。