不要落入trap of thinking a library should prescribe how to do everything。如果你想在 JavaScript 中做一些超时的事情,你需要使用setTimeout。 Redux 操作没有任何不同的理由。
Redux确实提供了一些处理异步内容的替代方法,但只有在意识到重复太多代码时才应该使用这些方法。除非您遇到此问题,否则请使用该语言提供的内容并寻求最简单的解决方案。
内联编写异步代码
这是迄今为止最简单的方法。并且这里没有任何特定于 Redux 的内容。
store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
store.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)
类似地,从连接组件内部:
this.props.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
this.props.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)
唯一的区别是,在连接的组件中,您通常无法访问 store 本身,但可以将 dispatch() 或特定的动作创建者作为道具注入。但是,这对我们没有任何影响。
如果您不喜欢在从不同组件调度相同动作时出现拼写错误,您可能希望提取动作创建者而不是内联调度动作对象:
// actions.js
export function showNotification(text) {
return { type: 'SHOW_NOTIFICATION', text }
}
export function hideNotification() {
return { type: 'HIDE_NOTIFICATION' }
}
// component.js
import { showNotification, hideNotification } from '../actions'
this.props.dispatch(showNotification('You just logged in.'))
setTimeout(() => {
this.props.dispatch(hideNotification())
}, 5000)
或者,如果您之前已将它们与connect() 绑定:
this.props.showNotification('You just logged in.')
setTimeout(() => {
this.props.hideNotification()
}, 5000)
到目前为止,我们还没有使用任何中间件或其他高级概念。
提取异步动作创建者
上面的方法在简单的情况下可以正常工作,但您可能会发现它存在一些问题:
- 它会强制您在要显示通知的任何位置复制此逻辑。
- 通知没有 ID,因此如果您足够快地显示两个通知,您将面临竞争条件。当第一个超时结束时,它会派发
HIDE_NOTIFICATION,错误地在超时之后隐藏第二个通知。
要解决这些问题,您需要提取一个函数来集中超时逻辑并分派这两个操作。它可能看起来像这样:
// actions.js
function showNotification(id, text) {
return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
return { type: 'HIDE_NOTIFICATION', id }
}
let nextNotificationId = 0
export function showNotificationWithTimeout(dispatch, text) {
// Assigning IDs to notifications lets reducer ignore HIDE_NOTIFICATION
// for the notification that is not currently visible.
// Alternatively, we could store the timeout ID and call
// clearTimeout(), but we’d still want to do it in a single place.
const id = nextNotificationId++
dispatch(showNotification(id, text))
setTimeout(() => {
dispatch(hideNotification(id))
}, 5000)
}
现在组件可以使用showNotificationWithTimeout,而无需重复此逻辑或具有不同通知的竞争条件:
// component.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')
// otherComponent.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged out.')
为什么showNotificationWithTimeout() 接受dispatch 作为第一个参数?因为它需要向 store 发送操作。通常一个组件可以访问dispatch,但是由于我们想要一个外部函数来控制调度,我们需要让它控制调度。
如果你有一个从某个模块导出的单例存储,你可以直接导入它并直接在其上dispatch:
// store.js
export default createStore(reducer)
// actions.js
import store from './store'
// ...
let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
const id = nextNotificationId++
store.dispatch(showNotification(id, text))
setTimeout(() => {
store.dispatch(hideNotification(id))
}, 5000)
}
// component.js
showNotificationWithTimeout('You just logged in.')
// otherComponent.js
showNotificationWithTimeout('You just logged out.')
这看起来更简单,但我们不推荐这种方法。我们不喜欢它的主要原因是它迫使 store 成为单例。这使得实现server rendering 变得非常困难。在服务器上,您会希望每个请求都有自己的存储,以便不同的用户获得不同的预加载数据。
单例商店也使测试变得更加困难。在测试动作创建者时,您不能再模拟商店,因为它们引用了从特定模块导出的特定真实商店。您甚至无法从外部重置其状态。
因此,虽然您在技术上可以从模块中导出单例存储,但我们不鼓励这样做。除非您确定您的应用永远不会添加服务器渲染,否则不要这样做。
回到以前的版本:
// actions.js
// ...
let nextNotificationId = 0
export function showNotificationWithTimeout(dispatch, text) {
const id = nextNotificationId++
dispatch(showNotification(id, text))
setTimeout(() => {
dispatch(hideNotification(id))
}, 5000)
}
// component.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')
// otherComponent.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged out.')
这解决了逻辑重复的问题,并使我们免于竞争条件。
Thunk 中间件
对于简单的应用程序,该方法就足够了。如果您对中间件感到满意,请不要担心它。
但是,在较大的应用程序中,您可能会发现一些不便之处。
例如,我们不得不传递dispatch 似乎很不幸。这使得separate container and presentational components 变得更加棘手,因为任何以上述方式异步调度 Redux 操作的组件都必须接受 dispatch 作为道具,以便它可以进一步传递它。您不能再将动作创建者与connect() 绑定,因为showNotificationWithTimeout() 并不是真正的动作创建者。它不返回 Redux 操作。
此外,记住哪些函数是像showNotification() 这样的同步动作创建者以及哪些是像showNotificationWithTimeout() 这样的异步助手可能会很尴尬。您必须以不同的方式使用它们,并注意不要将它们弄错。
这就是找到一种方法来“合法化”这种将dispatch 提供给辅助函数的模式的动机,并帮助 Redux 将这种异步动作创建者“视为”普通动作创建者的特例 而不是完全不同的功能。
如果您仍然与我们在一起,并且您还发现您的应用存在问题,欢迎您使用Redux Thunk 中间件。
概括地说,Redux Thunk 教 Redux 识别实际上是函数的特殊类型的操作:
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
const store = createStore(
reducer,
applyMiddleware(thunk)
)
// It still recognizes plain object actions
store.dispatch({ type: 'INCREMENT' })
// But with thunk middleware, it also recognizes functions
store.dispatch(function (dispatch) {
// ... which themselves may dispatch many times
dispatch({ type: 'INCREMENT' })
dispatch({ type: 'INCREMENT' })
dispatch({ type: 'INCREMENT' })
setTimeout(() => {
// ... even asynchronously!
dispatch({ type: 'DECREMENT' })
}, 1000)
})
当这个中间件被启用时,如果你调度一个函数,Redux Thunk 中间件会给它dispatch 作为参数。它也会“吞下”这样的动作,所以不用担心你的 reducer 会收到奇怪的函数参数。你的 reducer 只会接收普通的对象动作——要么直接发出,要么由我们刚刚描述的函数发出。
这看起来不是很有用,是吗?不是在这种特殊情况下。但是它让我们可以将 showNotificationWithTimeout() 声明为常规的 Redux 操作创建者:
// actions.js
function showNotification(id, text) {
return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
return { type: 'HIDE_NOTIFICATION', id }
}
let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
return function (dispatch) {
const id = nextNotificationId++
dispatch(showNotification(id, text))
setTimeout(() => {
dispatch(hideNotification(id))
}, 5000)
}
}
请注意,该函数与我们在上一节中编写的函数几乎相同。但是它不接受 dispatch 作为第一个参数。相反,它返回一个接受dispatch 作为第一个参数的函数。
我们将如何在我们的组件中使用它?当然,我们可以这样写:
// component.js
showNotificationWithTimeout('You just logged in.')(this.props.dispatch)
我们正在调用异步操作创建者来获取只需要dispatch 的内部函数,然后我们传递dispatch。
然而这比原版更尴尬!我们为什么要走那条路?
因为我之前告诉过你。 如果启用了 Redux Thunk 中间件,则任何时候您尝试调度函数而不是操作对象时,中间件都会以 dispatch 方法本身作为第一个参数来调用该函数。
所以我们可以这样做:
// component.js
this.props.dispatch(showNotificationWithTimeout('You just logged in.'))
最后,分派一个异步动作(实际上是一系列动作)看起来与将单个动作同步分派到组件没有什么不同。这很好,因为组件不应该关心某些事情是同步发生还是异步发生。我们只是把它抽象出来。
请注意,由于我们“教”了 Redux 识别这些“特殊”动作创建者(我们称它们为 thunk 动作创建者),我们现在可以在任何我们会使用常规动作创建者的地方使用它们。例如,我们可以将它们与connect() 一起使用:
// actions.js
function showNotification(id, text) {
return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
return { type: 'HIDE_NOTIFICATION', id }
}
let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
return function (dispatch) {
const id = nextNotificationId++
dispatch(showNotification(id, text))
setTimeout(() => {
dispatch(hideNotification(id))
}, 5000)
}
}
// component.js
import { connect } from 'react-redux'
// ...
this.props.showNotificationWithTimeout('You just logged in.')
// ...
export default connect(
mapStateToProps,
{ showNotificationWithTimeout }
)(MyComponent)
Thunks 中的读取状态
通常,您的 reducer 包含用于确定下一个状态的业务逻辑。但是,reducer 仅在动作被调度后才开始。如果您在 thunk 操作创建器中有副作用(例如调用 API),并且您想在某些情况下阻止它怎么办?
不使用 thunk 中间件,您只需在组件内部进行以下检查:
// component.js
if (this.props.areNotificationsEnabled) {
showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')
}
但是,提取动作创建者的目的是将这种重复逻辑集中到许多组件中。幸运的是,Redux Thunk 为您提供了一种读取 Redux 存储当前状态的方法。除了dispatch,它还将getState 作为第二个参数传递给您从thunk 动作创建器返回的函数。这让 thunk 读取存储的当前状态。
let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
return function (dispatch, getState) {
// Unlike in a regular action creator, we can exit early in a thunk
// Redux doesn’t care about its return value (or lack of it)
if (!getState().areNotificationsEnabled) {
return
}
const id = nextNotificationId++
dispatch(showNotification(id, text))
setTimeout(() => {
dispatch(hideNotification(id))
}, 5000)
}
}
不要滥用这种模式。当有可用的缓存数据时,它有利于摆脱 API 调用,但它不是构建业务逻辑的一个很好的基础。如果您仅使用getState() 有条件地分派不同的操作,请考虑将业务逻辑放入reducer 中。
后续步骤
既然您对 thunk 的工作原理有了基本的了解,请查看使用它们的 Redux async example。
您可能会发现许多 thunk 返回 Promise 的示例。这不是必需的,但非常方便。 Redux 不关心你从 thunk 中返回什么,但它会为你提供来自 dispatch() 的返回值。这就是为什么您可以通过调用 dispatch(someThunkReturningPromise()).then(...) 从 thunk 返回 Promise 并等待它完成的原因。
您还可以将复杂的 thunk 动作创建者拆分为几个较小的 thunk 动作创建者。 thunks 提供的dispatch 方法本身可以接受thunks,因此您可以递归地应用该模式。同样,这最适合 Promises,因为您可以在此基础上实现异步控制流。
对于某些应用,您可能会发现自己的异步控制流要求过于复杂而无法用 thunk 来表达。例如,以这种方式编写时,重试失败的请求、使用令牌的重新授权流程或分步入职可能过于冗长且容易出错。在这种情况下,您可能希望查看更高级的异步控制流解决方案,例如 Redux Saga 或 Redux Loop。评估它们,比较与您的需求相关的示例,然后选择您最喜欢的示例。
最后,如果您没有真正的需要,请不要使用任何东西(包括 thunk)。请记住,根据要求,您的解决方案可能看起来很简单
store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
store.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)
除非您知道自己为什么要这样做,否则不要担心。