【发布时间】:2021-08-11 17:52:52
【问题描述】:
假设我们有一个Page-组件,它将通知的呈现委托给Notification-组件。 Page-component 的 render 方法包含以下内容...
{this.state.notifications &&
<Notifications
notifications={this.state.notifications}
removeNotifAt={index => this.setState(prevState => {
const copy = [...prevState.notifications]
copy.splice(index, 1)
return { notifications: copy }
})}
removeNotifyBy={id => this.setState(prevState => {
const copy = [...prevState.notifications]
const index = copy.findIndex((notif, _) => { return notif.id === id })
copy.splice(index, 1)
return { notifications: copy }
})}
/>
}
...您可能会注意到,Notifications 需要一些相当大的函数来改变其父级的状态。由于它们访问this.state,因此这些函数必须在Notifications 的父级中定义,在本例中为Page。
现在,可以想象多个页面都有需要渲染的通知,因此它们都必须复制代码上面的代码 sn-p。众所周知,重复代码是不好的,那么我们怎样才能最好地避免呢?
不可能将函数removeNotifyAt 和removeNotifyBy 提取到定义在Notifications.js 中的函数中,因为它们需要访问this.state。
那么,处理这种由于需要访问 this.state 而无法提取的重复函数的反应方式是什么?我想我不是第一个遇到这个问题的人,因为这是一个多么微不足道的案例。
【问题讨论】:
标签: javascript reactjs design-patterns components code-duplication