Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

我是这么理解redux的 #36

Open
incuisting opened this issue Sep 23, 2017 · 0 comments
Open

我是这么理解redux的 #36

incuisting opened this issue Sep 23, 2017 · 0 comments
Labels

Comments

@incuisting
Copy link
Owner

incuisting commented Sep 23, 2017

首先,正统意义上理解reudx是由三部分组成:store,reducer,action。
store是一个对象,它有四个主要的方法:

1、dispatch:

用于action的分发——在createStore中可以用middleware中间件对dispatch进行改造,比如当action传入dispatch会立即触发reducer,有些时候我们不希望它立即触发,而是等待异步操作完成之后再触发,这时候用redux-thunk对dispatch进行改造,以前只能传入一个对象,改造完成后可以传入一个函数,在这个函数里我们手动dispatch一个action对象,这个过程是可控的,就实现了异步。

2、subscribe:

监听state的变化——这个函数在store调用dispatch时会注册一个listener监听state变化,当我们需要知道state是否变化时可以调用,它返回一个函数,调用这个返回的函数可以注销监听。 let unsubscribe = store.subscribe(() => {console.log('state发生了变化')})

3、getState:

获取store中的state——当我们用action触发reducer改变了state时,需要再拿到新的state里的数据,毕竟数据才是我们想要的。getState主要在两个地方需要用到,一是在dispatch拿到action后store需要用它来获取state里的数据,并把这个数据传给reducer,这个过程是自动执行的,二是在我们利用subscribe监听到state发生变化后调用它来获取新的state数据,如果做到这一步,说明我们已经成功了。

4、replaceReducer:

替换reducer,改变state修改的逻辑。
store可以通过createStore()方法创建,接受三个参数,经过combineReducers合并的reducer和state的初始状态以及改变dispatch的中间件,后两个参数并不是必须的。store的主要作用是将action和reducer联系起来并改变state。

action:

action是一个对象,其中type属性是必须的,同时可以传入一些数据。action可以用actionCreactor进行创造。dispatch就是把action对象发送出去。

reducer:

reducer是一个函数,它接受一个state和一个action,根据action的type返回一个新的state。根据业务逻辑可以分为很多个reducer,然后通过combineReducers将它们合并,state树中有很多对象,每个state对象对应一个reducer,state对象的名字可以在合并时定义。

先copy过来这么多基本概念。
emmm....反正我第一次就是晕的不行。
然后我看到了一张关系图,如下
image
我仿佛突然脑子中有了一个奇特的理解。
首先把store比作一个鱼塘,那么state就是鱼塘里的鱼。ActionCreators就是这个鱼塘的鱼塘主,他的手下有一个叫reducer的苦力机器人来帮他打理鱼塘。reducer机器人会根据鱼塘主ActionCreators的发出(dispatch)的指令(action),来对鱼塘(store)里的鱼(state)进行操作,但是reducer机器人的操作有一个特点就是它根据指令(action)的type返回新的鱼(state)。

大致如下图:
default

以上就是我对redux的store,action,reducer 的理解,其他的几个属性自行脑补。。

@incuisting incuisting changed the title redux 我是这么理解redux的 Sep 23, 2017
@incuisting incuisting changed the title 我是这么理解redux的 我是这么理解redux的(草稿) Sep 23, 2017
@incuisting incuisting changed the title 我是这么理解redux的(草稿) 我是这么理解redux的 Oct 3, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant