【问题标题】:How to deal with duplicated function code that alters parent state如何处理改变父状态的重复功能代码
【发布时间】: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。众所周知,重复代码是不好的,那么我们怎样才能最好地避免呢?

不可能将函数removeNotifyAtremoveNotifyBy 提取到定义在Notifications.js 中的函数中,因为它们需要访问this.state

那么,处理这种由于需要访问 this.state 而无法提取的重复函数的反应方式是什么?我想我不是第一个遇到这个问题的人,因为这是一个多么微不足道的案例。

【问题讨论】:

    标签: javascript reactjs design-patterns components code-duplication


    【解决方案1】:

    您可以将代码从 removeNotifyBy 和 removeNotifyBy 移动到函数中,并将它们放置在父组件中。然后你可以将它们作为道具传递给子组件。

    【讨论】:

      【解决方案2】:

      您可以将这些函数提取到 Notifications.js 中。 (如果您不想在父组件中编写这些函数)。 父母的状态和设置状态的函数都可以作为道具传递给通知组件。

      例子:

      <Notifications parentState={this.state} parentStateHandler={this.setState} />
      

      //注意:理想情况下,props 不应该这样命名,并且必须避免将整个 state 对象作为 prop 传递,而是应该将其拆分为子组件所需的 props。然而,这只是为了让您清楚地了解如何在孩子中访问父母的状态

      现在 Notifications 组件具有完整的父状态,可以通过 props.parentState 访问,您还可以使用 props.parentStateHandler 而不是 this.setState 来设置父状态

      【讨论】:

        猜你喜欢
        • 2021-03-15
        • 2019-06-17
        • 2013-10-07
        • 2021-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-15
        • 2016-07-19
        相关资源
        最近更新 更多