假设我有一个像这样的 react 组件:
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 状态做任何事情,或者我只是不关心它?
最佳答案
对于您的特定示例,我会避免创建 Redux 操作,因为如果 DO_PRINT
仅调用 window.print()
则无需更新任何状态>.
事实上,假设您正在创建一个“打印按钮”组件,我会将其重新定义为一个愚蠢的组件。 (参见differences between presentationl and container components。)
import React from ‘react’;
const PrintButton = () => {
const onClick = () => {
window.print();
};
return <button onClick={onClick}>Click Me</button>
};
export default PrintButton;
仅供引用,上面的代码可能不是为无状态组件声明事件处理程序的最有效方法,因为每次渲染组件时都会调用该函数。可能有更好(更有效)的方法( described in another SO question ),但这超出了这个问题。
关于javascript - 如何组织不修改状态的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44234224/