如何组织不修改状态的行为?

时间:2017-05-29 03:29:26

标签: javascript reactjs redux action

让我们说我有一个像这样的反应组件:

class App extends Component {
  print = () => {
    const { url } = this.props
    const frame = document.createElement('iframe')

    frame.addEventListener('load', () => {
      const win = frame.contentWindow

      win.focus()
      win.print()
      win.addEventListener('focus', () => document.body.removeChild(frame))
    })

    Object.assign(frame.style, {
      visibility: 'hidden',
      position: 'fixed',
      right: 0,
      bottom: 0
    })

    frame.src = url

    document.body.appendChild(frame)
  }

}

基本上,单击按钮会在浏览器中为用户调用打印功能。在这样的情况下,我是否仍然将其变为像DO_PRINT这样的redux动作,它实际上对我的redux状态没有任何作用,或者我是否只是不打扰它?

1 个答案:

答案 0 :(得分:1)

对于您的特定示例,我将避免创建Redux操作,因为如果DO_PRINT只调用window.print(),则import React from ‘react’; const PrintButton = () => { const onClick = () => { window.print(); }; return <button onClick={onClick}>Click Me</button> }; export default PrintButton; 无需更新任何状态。

事实上,假设您正在创建一个“打印按钮”组件,我会将其重新定义为一个愚蠢的组件。 (见differences between presentationl and container components。)

updateItem(...)

仅供参考,上面的代码可能不是为无状态组件声明事件处理程序的最有效方法,因为每次呈现组件时都会调用函数。可能有更好(更有效)的方式(described in another SO question),但这超出了这个问题。