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

如何实现异步action(即引入redux的react项目如何使用异步ajax) #6

Open
ckinmind opened this issue Feb 7, 2017 · 2 comments

Comments

@ckinmind
Copy link
Owner

ckinmind commented Feb 7, 2017

问题

@ckinmind
Copy link
Owner Author

ckinmind commented Feb 8, 2017

参考资料:阮一峰:Redux 入门教程(二):中间件与异步操作

为了理解中间件,让我们站在框架作者的角度思考问题:如果要添加功能,你会在哪个环节添加?
(1)Reducer:纯函数,只承担计算 State 的功能,不合适承担其他功能,也承担不了,因为理论上,纯函数不能进行读写操作
(2)View:与 State 一一对应,可以看作 State 的视觉层,也不合适承担其他功能。
(3)Action:存放数据的对象,即消息的载体,只能被别人操作,自己不能进行任何操作。
想来想去,只有发送 Action 的这个步骤,即store.dispatch()方法,可以添加功能

这里解释了中间件的添加位置,因为是在发送action的这个阶段,在这个阶段去处理异步请求,然后在ajax的回调中再dispatch对应的action

@ckinmind
Copy link
Owner Author

ckinmind commented Feb 8, 2017

在action文件中做出变化,本来在actions文件中定义了一些action creator, 用来生成一个action对象返回,然后dispatch这个对象到store中,现在这个action creator不返回一个对象而是返回一个函数,这个函数中是ajax的代码和其回调函数,这意味着原来dispatch一个对象,现在为了处理异步dispatch了一个函数,为了使得dispatch能够发送一个函数,需要用到redux-thunk这个库对dispatch方法做一个改造,使得dispatch可以接受函数作为参数.

参考资料:阮一峰:Redux 入门教程(二):中间件与异步操作

Action 是由store.dispatch方法发送的。而store.dispatch方法正常情况下,参数只能是对象,不能是函数
这时,就要使用中间件redux-thunk, redux-thunk中间件,改造store.dispatch,使得后者可以接受函数作为参数, 因此,异步操作的第一种解决方案就是,写出一个返回函数的 Action Creator,然后使用redux-thunk中间件改造store.dispatch

参考资料: 我们为什么要用 redux-thunk

如果 redux-thunk 发现 dispatch 了一个函数, 他会传给函数一个 dispatch 参数,这解决了 dispatch 不好获取的问题, 他会自己「吃掉」这个函数,不会传递给 reduces,防止 reduces 遇到一个函数而不知所措
我们可以看到,dispatch 一个异步 action 和 dispatch 一个同步的 action 是一致的,component 不用关系这个 action 是异步还是同步的,你可以在任何时间修改他

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant