为什么使用Redux Thunk然后可以做这样的事情:
ReadableAPI.getCategories().then((categories)=>{
console.log('after getCategories', categories)
this.props.dispatch(addCategories(categories))
})
Run Code Online (Sandbox Code Playgroud)
这不是更直接,并实现同样的事情?
我已经使用redux大约两个月了,并且刚刚开始探索处理异步行为的不同方法,例如获取数据.从文档和GitHub的讨论看来,通过使用thunk中间件来实现这一点的标准方法是一个非常简单的概念但是我不确定我是否理解将执行异步状态机的责任交给redux的好处中间件,可以使用简单的独立功能.
function fetchPosts(reddit) {
return dispatch => {
dispatch(requestPosts(reddit))
return fetch(`http://www.reddit.com/r/${reddit}.json`)
.then(response => response.json())
.then(json => dispatch(receivePosts(reddit, json)))
}
}
Run Code Online (Sandbox Code Playgroud)
然后可能在ReactJS组件中可能有一个按钮,如下面的按钮.
<button onClick={() => this.props.dispatch(fetchPosts(this.props.reddit))} />
Run Code Online (Sandbox Code Playgroud)
单击此按钮会调用异步操作创建者requestPosts,该函数返回接受调度的函数,并负责执行任何可能具有副作用的异步代码,并调度可能导致的真实操作.
虽然以上内容完全可以理解,但不清楚为什么人们不愿意做一些稍微简单化的事情,如下例所示.
function fetchPosts(dispatch, reddit) {
dispatch(requestPosts(reddit))
return fetch(`http://www.reddit.com/r/${reddit}.json`)
.then(response => response.json())
.then(json => dispatch(receivePosts(reddit, json)))
}
Run Code Online (Sandbox Code Playgroud)
<button onClick={() => fetchPosts(this.props.dispatch, this.props.reddit)} />
Run Code Online (Sandbox Code Playgroud)
基于这两个示例,我并没有看到使用thunk中间件的异步动作创建者如何购买任何东西,它需要在设置middlware时增加复杂性并引入两种动作创建者(1)返回单个的纯函数要发送的动作(2)不正确的功能,将动作和其他可能的响应反馈给调度员.我觉得我在这里遗漏的东西可以解释在redux中调度除了不可变动作之外的其他东西的好处.