基于Redux存储更改的操作(播放声音)

Ste*_*che 3 reactjs redux react-redux

我正在构建一个应用程序,其中包含一个带有状态树"提供"部分的商店(ImmutableJS列表对象).每当项目添加到此列表时,我需要采取一些操作(播放浏览器声音).可以通过几种不同类型的Redux操作将项添加到此列表中.

我试图找出对商店特定部分的变化作出反应的最佳方法.我可以在每个动作/减速器方法中执行此操作,但之后我会把它放在所有地方.我宁愿有一个处理逻辑的中心位置.

处理这个问题的最佳方法是什么?我应该创建一个通用商店订阅者并拥有自己的逻辑来跟踪列表值吗?

小智 8

在这种情况下,最好的选择是商店听众.简单侦听器函数或redux连接的React组件.

假设一个简单的功能来制造噪音:

function playSound () {
  const audio = new Audio('audio_file.mp3')
  audio.play()
}
Run Code Online (Sandbox Code Playgroud)

您可以创建商店观察者并监听更改:

function createSoundObserver (store) {
  let prevState = store.getState()

  return store.subscribe(() => {
    const nextState = store.getState()

    if (prevState.messages.length < nextState.messages.length) {
      playSound()
    }

    prevState = nextState
  })
}
Run Code Online (Sandbox Code Playgroud)

您可以使用React组件实现相同的功能:

import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

class Notifier extends Component {

  static propTypes = {
    messages: PropTypes.array.isRequired
  }

  componentDidUpdate (prevProps) {
    if (this.props.messages.length > prevProps.messages.length) {
      playSound()
    }
  }

  render () { return null }
}

export default connect((state, props) => {
  const {messages} = state
  return {messages}
}, {})(Notifier)
Run Code Online (Sandbox Code Playgroud)

只要渲染树中存在通知程序,它就会检查更改并相应地播放声音.这种方法的优点是,如果您想保持安静,则无需额外注意取消订阅事件,并且无缝地处理服务器端呈现.